Skip to content

Instantly share code, notes, and snippets.

@osteslag
Created August 14, 2018 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osteslag/085b1265fb3c6a23b60c318b15922185 to your computer and use it in GitHub Desktop.
Save osteslag/085b1265fb3c6a23b60c318b15922185 to your computer and use it in GitHub Desktop.
Swift Playground for updating an image file’s metadata without re-processing the image.
// Adapted from Apple's Tech Note, [Modifying Image Metadata Without Recompressing Image](https://developer.apple.com/library/archive/qa/qa1895/_index.html).
import Cocoa
import ImageIO
let url = URL(fileURLWithPath: "/path/to/file.tiff")
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { fatalError("Cannot create URL") }
guard var properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? Dictionary<CFString, Any> else { fatalError("Cannot get image properties") }
properties[kCGImageDestinationDateTime] = Date()
properties[kCGImagePropertyIPTCDictionary] = [kCGImagePropertyIPTCSpecialInstructions: "ABC"]
print(properties)
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
fatalError("Error: could not create image source for \(url.absoluteString)")
}
let uti = CGImageSourceGetType(source) ?? "public.tiff" as CFString
let tempUrl = url.deletingLastPathComponent().appendingPathComponent("temp.tiff")
guard let destination = CGImageDestinationCreateWithURL(tempUrl as CFURL, uti, 1, nil) else {
fatalError("Error: could not create image destination for \(url.absoluteString)")
}
var error: Unmanaged<CFError>?
withUnsafeMutablePointer(to: &error) { errorPtr in
guard CGImageDestinationCopyImageSource(destination, source, properties as CFDictionary?, errorPtr) else {
fatalError("Error: could not copy image data from \(url.absoluteString): \(String(describing: errorPtr.pointee.debugDescription))")
}
}
print("kCGImagePropertyIPTCSpecialInstructions are not written to \(tempUrl.absoluteString)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment