Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modifying EXIF Data with Swift 3
//: Playground - noun: a place where people can play
import UIKit
import ImageIO
import MobileCoreServices
let TEST_IMAGE: String = "replace.jpg"
let beach: UIImage = UIImage(named: TEST_IMAGE)!
let imageData: Data = UIImageJPEGRepresentation(beach, 1)!
let cgImgSource: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil)!
let uti: CFString = CGImageSourceGetType(cgImgSource)!
let dataWithEXIF: NSMutableData = NSMutableData(data: imageData)
let destination: CGImageDestination = CGImageDestinationCreateWithData((dataWithEXIF as CFMutableData), uti, 1, nil)!
let imageProperties = CGImageSourceCopyPropertiesAtIndex(cgImgSource, 0, nil)! as NSDictionary
let mutable: NSMutableDictionary = imageProperties.mutableCopy() as! NSMutableDictionary
var EXIFDictionary: NSMutableDictionary = (mutable[kCGImagePropertyExifDictionary as String] as? NSMutableDictionary)!
print("before modification \(EXIFDictionary)")
EXIFDictionary[kCGImagePropertyExifUserComment as String] = "type:video"
mutable[kCGImagePropertyExifDictionary as String] = EXIFDictionary
CGImageDestinationAddImageFromSource(destination, cgImgSource, 0, (mutable as CFDictionary))
CGImageDestinationFinalize(destination)
let testImage: CIImage = CIImage(data: dataWithEXIF as Data, options: nil)!
let newproperties: NSDictionary = testImage.properties as NSDictionary
print("after modification \(newproperties)")
@avrhack

This comment has been minimized.

avrhack commented May 12, 2017

Only down side to this example is that it will recompress the image so you lose quality every time you change the metadata. The only way to avoid that is to use the CGImageDestinationCopyImageSource routine and that takes a much more challenging-to-create set of metadata options.

Apple technical note here refers: https://developer.apple.com/library/content/qa/qa1895/_index.html

I've proved this by comparing the resulting files by converting each to uncompressed TIFF and then stripping all metadata. The one created with CopyImageSource is identical to the original whereas the one created AddImageFromSource using your snippet above is changed ie recompressed.

@nsnick

This comment has been minimized.

nsnick commented Jun 6, 2017

Is there an example anywhere with the metadata part? I tried Apple's example and CGImageDestinationFinalize fails.

@vijayradke

This comment has been minimized.

vijayradke commented Sep 27, 2018

How can we save the images after modifying metadata in document directory?
I tried to save but image saved with old metadata. Modified metadata is lost and image has only original metadata.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment