简体   繁体   中英

Save image taken with UIImagePickerController to photo roll in HEIC format

If I save an image to the photo roll with the methods I know ( UIImageWriteToSavedPhotosAlbum() and [PHAssetChangeRequest creationRequestForAssetFromImage:img] ) a subsequent choosing of the saved photo with the UIImagePickerController gives me a .jpg image.

info[UIImagePickerControllerReferenceURL] gives assets-library://asset/asset.JPG?id=B8B231DC-3A84-4F65-AD5E-D6C431CB5F8B&ext=JPG

and

[((PHAsset*)info[UIImagePickerControllerPHAsset]) valueForKey:@"filename"] gives me @"IMG_5512.JPG" for example.

However if I shoot a photo with the "Camera" app, that photo chosen with UIImagePickerController has the HEIC extension (given that the "High Efficiency" setting is effective in the "Camera" settings).

So what is a convenient way to save in HEIC format to the photo roll in response to - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info ?

Thanks to Matt comments I was able to solve the issue. There is a very similar question at How to save image taken from UIImagePickerController as HEIF file? , but not exactly the same.

UIImage* img=(UIImage*)info[UIImagePickerControllerOriginalImage];
NSDictionary* meta=(NSDictionary*)info[UIImagePickerControllerMediaMetadata];
CIContext* ctx=[CIContext context];
CIImage* ci=[[CIImage alloc] initWithImage:img options:@{kCIImageProperties:meta}];
NSData* heicData=[ctx HEIFRepresentationOfImage:ci format:kCIFormatRGBA8 colorSpace:ctx.workingColorSpace options:@{}];
NSString* __block newId=nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
  [request addResourceWithType:PHAssetResourceTypePhoto data:heicData options:nil];
  newId = request.placeholderForCreatedAsset.localIdentifier;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
  if (success) {
    PHFetchResult* fr=[PHAsset fetchAssetsWithLocalIdentifiers:@[newId] options:nil];
    PHAsset* phass=fr.firstObject;
    NSLog(@"PHAsset:%@",phass);
  } else {
    NSLog(@"error:%@",error);
  }
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM