【學習ios之路:UI系列】獲取通過UIImagePackerController獲取的系統相簿圖片的名稱資訊及儲存系統相簿到本地
阿新 • • 發佈:2019-01-28
通過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];
}];
}
原文地址:點選