【学习ios之路:UI系列】获取透过UIImagePackerController获取的系统相册图片的名称信息及保存系统相册到本地
【学习ios之路:UI系列】获取通过UIImagePackerController获取的系统相册图片的名称信息及保存系统相册到本地
通过IUImagePickerController方法获取系统的相册,而想要得到从系统相册得到的图片的信息需要以下几步:
1:获得从UIImagePicker选择的照片的Assert;
2:得到Assert的ALAssertRepresentation;
3:ALAssertRepresentation有个filename的属性
代码具体如下:
该方法是UIImagePickerController中的代理中的方法
<span style="font-size:18px;"> - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL]; ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { ALAssetRepresentation *representation = [myasset defaultRepresentation]; NSString *fileName = [representation filename]; NSLog(@"fileName : %@",fileName); }; ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; [assetslibrary assetForURL:imageURL resultBlock:resultblock failureBlock:nil]; } </span>注:想要用到以上操作,需要引入以下的内容
<span style="font-size:18px;">#import <AssetsLibrary/ALAsset.h> #import <AssetsLibrary/ALAssetsLibrary.h> #import <AssetsLibrary/ALAssetsGroup.h> #import <AssetsLibrary/ALAssetRepresentation.h></span>如下效果:
2.获取系统相册中的图片,将图片保存到本地
注:转化为NSData类型来保存图片,代码如下:
//保存图片 方法1 //NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //NSString*documentsDirectory=[paths objectAtIndex:0]; //NSString*aPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",@"test"]]; //方法2 //NSHomeDirectory(),方法是获取沙盒根路径,test是自定义图片名,可用上述方法中获取的名字替换 NSString *aPath=[NSString stringWithFormat: @"%@/Documents/%@.jpg",NSHomeDirectory(),@"test"]; //image是对应的图片,即图片通过UIPickerController获取系统相册图 NSData *imgData = UIImageJPEGRepresentation(image,0); //保存到当地文件中 [imgData writeToFile:aPath atomically:YES];
整理以上代码如下:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { //获取正在编辑的图片 UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage]; self.imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL]; //获取图片的名字信息 ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { ALAssetRepresentation *representation = [myasset defaultRepresentation]; self.imageName = [representation filename];//self.imageName是属性 }; ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; [assetslibrary assetForURL:self.imageUrl resultBlock:resultblock failureBlock:nil]; //将图片添加到新的视图上 self.imageView.image = image; [self dismissViewControllerAnimated:YES completion:^{ //获取图片的类型前的名字,将字符串切割操作 NSString *imagePath = [[self.imageName componentsSeparatedByString:@"."] firstObject]; NSString *aPath=[NSString stringWithFormat:@"%@/Documents/%@.jpg", NSHomeDirectory(),imagePath]; NSData *imgData = UIImageJPEGRepresentation(image,0); [imgData writeToFile:aPath atomically:YES]; }]; }
原文地址:点击