Created
February 1, 2017 14:10
-
-
Save kwylez/a4b6ec261e52970e1fa5dd4ccfe8898f to your computer and use it in GitHub Desktop.
Modifying EXIF Data with Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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)") |
Is there an example anywhere with the metadata part? I tried Apple's example and CGImageDestinationFinalize fails.
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
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.