1

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 ?

Leo
  • 925
  • 10
  • 24
  • @matt I'm not really familiar with the internals of UIImage. Are you referring to ```let rawData = myImage.cgImage?.dataProvider?.data as Data?``` like mentioned in https://stackoverflow.com/questions/4623931/get-underlying-nsdata-from-uiimage ? – Leo Mar 13 '20 at 15:59
  • 1
    https://stackoverflow.com/questions/47470419/how-to-save-image-taken-from-uiimagepickercontroller-as-heif-file Tells you how to get the HEIF data, and then, as I said before, you should be able to create the asset from that data. – matt Mar 13 '20 at 16:27
  • @matt great, that works ! I never used CIImage before, so without the pointer I wouldn't have solved it. I wonder why here is no such thing like ```UIImageHEIFRepresentation``` to have something more high level. – Leo Mar 13 '20 at 16:52

1 Answers1

1

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);
  }
}]
Leo
  • 925
  • 10
  • 24