Memory Leak when using ImageIO to convert a UIImage and it's metadata to a Data object

Viewed 112

I have a UIImage object and some Exif data I need to preserve on a separate dictionary. I'm combining both of those to a Data object using this method:

    static func convert(image: UIImage, imageMetadata: [String: Any]) -> Data {
        var imageMetadata = imageMetadata
        imageMetadata[kCGImagePropertyTIFFOrientation as String] = image.imageOrientation.rawValue
        if var tiff = imageMetadata[kCGImagePropertyTIFFDictionary as String] as? [String: Any] {
            tiff[kCGImagePropertyOrientation as String] = image.imageOrientation.rawValue
            imageMetadata[kCGImagePropertyTIFFDictionary as String] = tiff
        }
        let destData = NSMutableData() as CFMutableData
        if let data = image.jpegData(compressionQuality: 0.2) as NSData?,
           let imageSource = CGImageSourceCreateWithData(data, nil),
           let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil),
           let destination = CGImageDestinationCreateWithData(
            destData as CFMutableData,
            kUTTypeJPEG,
            1,
            nil) {
            CGImageDestinationAddImage(destination, cgImage, imageMetadata as CFDictionary)
            CGImageDestinationFinalize(destination)
        } else {
            assertionFailure("can't attach exif")
        }
        
        return destData as Data
    }

The method itself works and the output is the expected output, however, for some reason, there's a memory leak after performing this operation and I can't seem to find the root cause (Instruments didn't really help - it just helped me to find that this method was causing the leak).

Any idea what's causing the memory leak and how can I prevent it? (tried forcing an autoreleasepool as well but that didn't change anything).

0 Answers
Related