获取图片名称,
一、要求
1、获取相册图片名称
2、获取拍照图片名称
二、实现
本次记录的方法是调用系统相册、相机后,获取图片名称的实现
相册、相机调用就不写上去了。直接上获取名称的代码
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] fixOrientation];
//相机拍摄获取
if(@available(iOS9.0, *)) {
//唯一标识,可以用于图片资源获取
__blockNSString*createdAssetID =nil;
XZWeakSelf(weakSelf);
[[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
PHAssetChangeRequest *changeAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
createdAssetID = changeAssetRequest.placeholderForCreatedAsset.localIdentifier;
}completionHandler:^(BOOLsuccess,NSError*_Nullableerror) {
//获取图片内容信息必须要放在completionHandler后。不然可能拿不到
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetID] options:nil];
PHAsset*asset = fetchResult.firstObject;
NSString*filename = [assetvalueForKey:@"filename"];
if(![NSStringstrNilOrEmpty:filename]) {
//判空
[weakSelfp_cameraWithInfo:infofileName:filename];
}else{
//失败
}
}];
}else{
XZWeakSelf(weakSelf);
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[libwriteImageToSavedPhotosAlbum:image.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
if(error) {
NSLog(@"error:%@", error);
}else{
PHFetchResult*fetchResult = [PHAssetfetchAssetsWithALAssetURLs:@[assetURL]options:nil];
PHAsset*asset = fetchResult.firstObject;
NSString*filename = [assetvalueForKey:@"filename"];
if(![NSStringstrNilOrEmpty:filename]) {
[weakSelfp_cameraWithInfo:infofileName:filename];
}
}
}];
}
}else{
//相册获取
[self p_photoLibraryWithInfo:info];
}
}
//相册选择
- (void)p_photoLibraryWithInfo:(NSDictionary<NSString *,id> *)info{
NSString*imageName =@"";
NSString*imageType =@"";
//给前端压缩一下图片Jpeg格式
NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
if(imageUrl) {
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[imageUrl] options:nil];
PHAsset*asset = fetchResult.firstObject;
NSString*filename = [assetvalueForKey:@"filename"];
if(![NSStringstrNilOrEmpty:filename]) {
UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] fixOrientation];
imageName = [filenamestringByDeletingPathExtension];
imageType = [filenamepathExtension];
}else{
//失败
}
}
}
//相机选择
- (void)p_cameraWithInfo:(NSDictionary *)infofileName:(NSString*)fileName {
NSString *imageName = [fileName stringByDeletingPathExtension];//名称
NSString*imageType = [fileName pathExtension];//类型
UIImage *image = [[info objectForKey:UIImagePickerControllerOriginalImage] fixOrientation];
}
网友评论