Created
August 14, 2018 16:55
-
-
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.
This file contains hidden or 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
// 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