There is a simple application, on the storyboard added UIImageView and button
Button opens the photo gallery, and I choose an image and eventually it appears on the UIimaeView
But when I kill the application snapshot is not saved What to do?
this my code :
-(IBAction)takePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.image.image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
ok. try this:
#import "ViewController.h"
#import AssetsLibrary;
#interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) UIImagePickerController *picker;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSURL *selectedImageURL = [NSURL URLWithString:[userDefaults objectForKey:#"selectedImageURL"]];
if (selectedImageURL) {
[self getImageFromAssetsAtURL:selectedImageURL completion:^(UIImage *image, NSError *error) {
if (!error && image) {
self.imageView.image = image;
}
}];
}
}
- (IBAction)pickImage:(UIButton *)sender {
[self presentViewController:self.picker animated:YES completion:nil];
}
- (UIImagePickerController *)picker {
if (!_picker) {
_picker = [UIImagePickerController new];
_picker.delegate = self;
_picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
return _picker;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
NSURL *selectedImageURL = info[UIImagePickerControllerReferenceURL];
// set image
self.imageView.image = selectedImage;
// save image url
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:selectedImageURL.absoluteString forKey:#"selectedImageURL"];
[userDefaults synchronize];
// dismiss
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getImageFromAssetsAtURL:(NSURL *)imageURL completion:(void (^)(UIImage *, NSError *))completion {
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
completion(image, nil);
} failureBlock:^(NSError *error) {
completion(nil, error);
}];
}
#end
since the AssetsLibrary is deprecated as of iOS 9.0 you could and should use the Photos framework instead. you have to import it...
#import Photos;
and change the getImageFromAssetsAtURL... method to the following:
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[imageURL] options:nil];
if (result.count == 1) {
PHAsset *asset = result.firstObject;
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
UIImage *selectedImage = [UIImage imageWithData:imageData];
completion(selectedImage, nil);
}];
} else {
completion(nil, nil);
}
Finally I used this code.
-(void)viewDidLoad {
[super viewDidLoad];
[self loadDefaultImage];
}
-void)viewDidAppear:(BOOL)animated
{
[self loadDefaultImage];
}
- (IBAction)TakePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
//append filename to document directory url
NSURL *urlSave = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
//do something to previously taken image (in this case: delete it)
if ([[NSFileManager defaultManager] fileExistsAtPath:urlSave.path]) {
[[NSFileManager defaultManager] removeItemAtPath:urlSave.path error:nil];
}
//save image to document directory
[UIImagePNGRepresentation(image) writeToFile:urlSave.path atomically:YES];
//optional: save image to photo library
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
-(NSURL *)getDocumentsPathURL
{
//document directory of app
return [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
}
-(void)loadDefaultImage
{
NSURL *urlImage = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
if ([[NSFileManager defaultManager] fileExistsAtPath:urlImage.path]) {
NSData *dataFile = [[NSFileManager defaultManager] contentsAtPath:urlImage.path];
UIImage *image = [UIImage imageWithData:dataFile];
[_imageView setImage:image];
}
else {
NSLog(#"Image not found");
}
}
Related
I am new in Objective-C and I want choose one image from a Gallery and I want get the name and the extension and copy that image to my project folder.
Use UIimagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([mediaTypeStr isEqualToString:#"photo"])
{
if ([info objectForKey:UIImagePickerControllerOriginalImage])
{
// images = [NSMutableArray arrayWithCapacity:[info count]];
_images = [[NSMutableArray alloc]init];
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];;
img =[self scaleAndRotateImage:img];
[_images addObject:img];
// Save Photo to library only if it wasnt already saved i.e. its just been taken
[self.alAsstlibrary saveImage:img toAlbum:#"FOlder name" completion:^(NSURL *assetURL, NSError *error)
{
if (error!=nil)
{
//NSLog(#"Big error: %#", [error description]);
}
} failure:nil];
}
else
{
//NSLog(#"UIImagePickerControllerReferenceURL = %#", info);
}
}
[picker dismissViewControllerAnimated:YES completion:Nil];
}
write these in viewdidload or on the buttons click event as per your need..
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;//by writing YES here you can edit image also..
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
imgview=[[UIImageView alloc]initWithFrame:CGRectMake(x+y, y, width, height)];
[imgview setTag:i];
imgview.contentMode = UIViewContentModeScaleAspectFill;
[imgview setClipsToBounds:YES];
[self.view addSubview:imgview];
write these in your .m file..
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//if you write picker.allowsEditing = YES; than write info[UIImagePickerControllerEditedImage] in BELOW line....
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
imgview.image = chosenImage;//set selected image in your imageview
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
i hope it helps..
To achieve this follow these steps.
Get the image
- (void) getPicture:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];
}
You will get the image in imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self save:image];
[picker dismissModalViewControllerAnimated:YES];
}
Save image in documents
-(void)save:(UIImage*)image
{
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
}
Get document path
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
Get the Image
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];
I'm trying to pick a video from PhotoAlbum. I'm using the UIImagePickerController but every time after i chose the video UIImagePickerControllerMediaURL is returning nil.
What I am missing?
Thanks.
- (IBAction)galerry:(id)sender {
self.imagePickerController = [[UIImagePickerController alloc] init];
[self.imagePickerController setDelegate:self];
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
self.imagePickerController.mediaTypes =#[(NSString *)kUTTypeMovie,(NSString *)kUTTypeVideo];
[self.imagePickerController setVideoMaximumDuration:20];
self.imagePickerController.allowsEditing = YES;
[self presentViewController:self.imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSURL *videoURL= [info objectForKey:UIImagePickerControllerMediaURL];
NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
NSString *moviePath = [videoUrl path];
NSURL *imagePickerURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSURL *videoURL2= [info valueForKey:UIImagePickerControllerMediaMetadata];
// picker.videoQuality=UIImagePickerControllerQualityTypeMedium;
[picker dismissViewControllerAnimated:YES completion:^{
Edition *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"EditionVC"];
vc.videoUrl=videoURL;
[self presentViewController:vc animated:YES completion:nil];
}];
}
All variables returning nil (videoURL,videoUrl,imagePickerURL,videoURL2).
What is wrong here?
EDIT:
This is my info dictionary:
po info
{
UIImagePickerControllerMediaType = "public.movie";
UIImagePickerControllerReferenceURL = "assets-library://asset/asset.MOV?id=87B8D3F5-DE9C-4F06-A88B-5116055A618A&ext=MOV";
}
#import <MobileCoreServices/UTCoreTypes.h>
- (void)getVideo {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[ (NSString *) kUTTypeMovie ];
[self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = info[ UIImagePickerControllerMediaType ];
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSURL *videoUrl=(NSURL*) info[ UIImagePickerControllerMediaURL ];
NSString *moviePath = [videoUrl path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)xuanquButtonClicked:(JohnButtonLong*)button
{
_picker = [[UIImagePickerController alloc] init];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
JLActionManager * manager = [JLActionManager sharedInstance];
[manager showAndHideHUDWithTitle:nil detailText:#"亲,您的相册无法打开" inView:self.view];
return;
}
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_picker.allowsEditing = YES;
_picker.delegate = self;
[self presentViewController:_picker animated:YES completion:^{
}];
}
#pragma mark - UIIMagePickerController delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 如果没有选取 使用默认头像
_strHeadPic = #"";
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:^{
}];
// 选取了某个头像
UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
_img_touxiang.image = image;
//压缩图像
image = [self OriginImage:image scaleToSize:CGSizeMake(160, 160)];
NSData * img_data = UIImageJPEGRepresentation(image, 0.5);
//进行base64编码
NSData * data = [GTMBase64 encodeData:img_data];
_strHeadPic = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
// 压缩成指定大小
-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();// 是当前的context出对战
// 返回新的改变大小后的图片
return scaledImage;
}
UnitMyInfo * myInfo = GetMyInfo;
[_img_touxiang setImageWithURL:[NSURL URLWithString:BaseImgURL(myInfo.umi_URL)] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];
// First You have to get Url from Image then set url On SDWebImages.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
//Set Image On SDWebView.
[imageView setImageWithURL:[NSURL URLWithString:localFilePath] placeholderImage:[UIImage imageNamed:#"default_headImg.jpg"]];
I already wrote this code to make a profile photo for my app and it doesn't work. Been searching for different sources and couldn't find any.Please help. I can take a photo but it doesn't get saved on the Album and a photo can't be uploaded or saved on the UIImageView for the profile.
#import "ViewController.h"
#interface ViewController ()
{
UIImage *originalImage;
}
#property(nonatomic, weak) IBOutlet UIImageView *selectedImageView;
#property(nonatomic, weak) IBOutlet UIBarButtonItem *saveButton;
#end
#implementation ViewController
#synthesize selectedImageView, saveButton;
- (IBAction)photoFromAlbum
{
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:photoPicker animated:YES completion:NULL];
}
- (IBAction)photoFromCamera
{
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:photoPicker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)photoPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.saveButton.enabled = YES;
originalImage = [info valueForKey:UIImagePickerControllerOriginalImage];
[self.selectedImageView setImage:originalImage];
// [photoPicker dismissModalViewControllerAnimated:YES];
}
- (IBAction)saveImageToAlbum
{
UIImageWriteToSavedPhotosAlbum(self.selectedImageView.image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *alertTitle;
NSString *alertMessage;
if(!error)
{
alertTitle = #"Image Saved";
alertMessage = #"Image saved to photo album successfully.";
}
else
{
alertTitle = #"Error";
alertMessage = #"Unable to save to photo album.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:self
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
#end
This question already has answers here:
Getting image name of iphone photo library
(2 answers)
Closed 9 years ago.
I've searched how to get the name of the saved image takes from the camera, but i didn't find something simple.
this is my code :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if( [picker sourceType] == UIImagePickerControllerSourceTypeCamera){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
{
NSLog(#"IMAGE SAVED TO PHOTO ALBUM");
[library assetForURL:assetURL resultBlock:^(ALAsset *asset )
{
NSLog(#"we have our ALAsset!");
NSLog(#"%#", assetURL);
}
failureBlock:^(NSError *error )
{
NSLog(#"Error loading asset");
}];
}];
}
}
I you have the answer, i will happy to test it .
Thanks in advance.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *resourceURL;
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image =[[UIImage alloc] init];
image =[info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
NSString *imageName = [imagePath lastPathComponent];
resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
NSData *imageData;
NSString *extensionOFImage =[imageName substringFromIndex:[imageName rangeOfString:#"."].location+1 ];
if ([extensionOFImage isEqualToString:#"jpg"])
{
imageData = UIImagePNGRepresentation(image);
}
else
{
imageData = UIImageJPEGRepresentation(image, 1.0);
}
int imageSize=imageData.length/1024;
NSLog(#"imageSize--->%d", imageSize);
if (imageName!=nil) {
NSLog(#"imageName--->%#",imageName);
}
else
{
NSLog(#"no image name found");
}
}
If you are using ASSerts
-(void)assetPickerController:(WSAssetPickerController *)sender didFinishPickingMediaWithAssets:(NSArray *)assets
{
[self dismissViewControllerAnimated:YES completion:^{
if (assets.count < 1) return;
//self.pageControl.numberOfPages = assets.count;
int index = 0;
for (ALAsset *asset in assets) {
// NSString *imageName = [[asset defaultRepresentation] filename];
UIImage *image = [[UIImage alloc] initWithCGImage:asset.defaultRepresentation.fullScreenImage];
// (#"%#", [[asset defaultRepresentation] filename]);
NSData *imageData = UIImagePNGRepresentation(image);
int imageSize=imageData.length/1024;
(either)
NSURL *imagePath = [asset objectForKey:#"UIImagePickerControllerReferenceURL"];
// NSURL *imagePath = [NSURL URLWithString:[asset ob]];
NSString *imageName = [imagePath lastPathComponent];
(or)
NSLog(#"%#",[[asset defaultRepresentation] filename]);
index++;
}
}];
}
Try following code. I have used this in one of my previous project and its working for me :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
_selectedImage = info[UIImagePickerControllerEditedImage];
self.photoView.image = _selectedImage;
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(#"[imageRep filename] : %#", [imageRep filename]);
};
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
[picker dismissViewControllerAnimated:YES completion:NULL];
}