0

I am adding exif data to images on iPhone device using the following code:

func testPhoto(identifier: String) {
    let result =
        PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil)

    PHCachingImageManager
        .default()
        .requestImageData(for: result.firstObject!, options: nil) {
            (data, uti, orientation, info) in
            _ = self.addExif(data: data!)
    }
}

func addExif(data: Data) -> NSData? {
    let selectedImageSourceRef =
        CGImageSourceCreateWithData(data as CFData, nil)!

    let imagePropertiesDictionaryRef =
        CGImageSourceCopyPropertiesAtIndex(selectedImageSourceRef, 0, nil)

    var imagePropsDictionary: [String: Any] =
        imagePropertiesDictionaryRef as! [String : Any]

    var exifData = [String: Any]()

    let newImageData = NSMutableData()

    let imageDestination =
        CGImageDestinationCreateWithData(newImageData, kUTTypeJPEG, 1, nil)!

    exifData[kCGImagePropertyExifDateTimeOriginal as String] = NSDate()

    imagePropsDictionary[kCGImagePropertyExifDictionary as String] = exifData

    CGImageDestinationAddImageFromSource(
        imageDestination,
        selectedImageSourceRef,
        0,
        imagePropsDictionary as CFDictionary)

    if !CGImageDestinationFinalize(imageDestination) {
        NSLog("Could not finalize")
    }

    return newImageData
}

The method crashes when trying to finalize the destination data source (CGImageDestinationFinalize).

The app terminates due to memory pressure. This happens for huge images (20,000x20,000 pixels). Regular images pass through this method just fine.

Is there any way to add EXIF info to image without causing memory pressure?

Thanks!

UrK
  • 2,191
  • 2
  • 26
  • 42

1 Answers1

0

CGImageSource is designed to serve as a data source without having to load all the data into memory at once. Rather than using CGImageSourceCreateWithData, use CGImageSourceCreateWithURL(_:_:) to create an image source from a file on disk. The system will then manage streaming the data as needed without having to load it all into memory at once.

Duncan C
  • 128,072
  • 22
  • 173
  • 272