Write UIImage along with metadata (EXIF, GPS, TIFF) in iPhone's Photo library

后端 未结 8 1803
情歌与酒
情歌与酒 2020-11-29 05:12

I am developing a project, where the requirements are: - User will open the camera through the application - Upon capturing an Image, some data will be appended to the captu

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 05:36

    The problem we are trying to solve is: the user has just taken a picture with the UIImagePickerController camera. What we get is a UIImage. How do we fold metadata into that UIImage as we save it into the camera roll (photo library), now that we don't have the AssetsLibrary framework?

    The answer (as far as I can make out) is: use the ImageIO framework. Extract the JPEG data from the UIImage, use it as a source and write it and the metadata dictionary into the destination, and save the destination data as a PHAsset into the camera roll.

    In this example, im is the UIImage and meta is the metadata dictionary:

    let jpeg = UIImageJPEGRepresentation(im, 1)!
    let src = CGImageSourceCreateWithData(jpeg as CFData, nil)!
    let data = NSMutableData()
    let uti = CGImageSourceGetType(src)!
    let dest = CGImageDestinationCreateWithData(data as CFMutableData, uti, 1, nil)!
    CGImageDestinationAddImageFromSource(dest, src, 0, meta)
    CGImageDestinationFinalize(dest)
    let lib = PHPhotoLibrary.shared()
    lib.performChanges({
        let req = PHAssetCreationRequest.forAsset()
        req.addResource(with: .photo, data: data as Data, options: nil)
    })
    

    A good way to test — and a common use case — is to receive the photo metadata from the UIImagePickerController delegate info dictionary thru the UIImagePickerControllerMediaMetadata key and fold it into the PHAsset as we save it into the photo library.

提交回复
热议问题