我正在尝试修改 JPEG 图像中包含的元数据。它可以是图像中的任何元数据,在我的示例中,我尝试更改为DateTimeDigitized
财产到当前日期。
我的代码似乎大部分工作,但是设置的属性被删除而不是更改。我不确定为什么会发生这种情况,谁能告诉我我做错了什么?
我欢迎任何有关有助于执行任务的框架的建议,但我特别感兴趣的是我用这种方法做错了什么。
我在 Playground 中运行此代码,其中名为“foo.jpg”的图像存储在路径中~/Documents/Shared Playground Data/
.
import Foundation
import ImageIO // CGImage functions
import PlaygroundSupport
let ImagePropertyExifDictionary = kCGImagePropertyExifDictionary as String
let ImagePropertyExifDateTimeDigitized = kCGImagePropertyExifDateTimeDigitized as String
func updateEXIFDateDigitized() {
// Create URL for source and destination
let sourceURL = playgroundSharedDataDirectory.appendingPathComponent("foo.jpg") as CFURL
let destinationURL = playgroundSharedDataDirectory.appendingPathComponent("bar.jpg") as CFURL
// Read source and get properties
guard
let sourceRef = CGImageSourceCreateWithURL(sourceURL, nil),
var metadata = CGImageSourceCopyPropertiesAtIndex(sourceRef, 0, nil) as? [String:Any] else { return }
print("unmodified properties", metadata, separator:"\n")
// Modify EXIF DateTimeDigitized property
guard var exif = metadata[ImagePropertyExifDictionary] as? [String:Any] else { return }
exif[ImagePropertyExifDateTimeDigitized] = Date() as CFDate
metadata[ImagePropertyExifDictionary] = exif as CFDictionary
print("", "modified properties", metadata, separator:"\n")
// Set up destination
guard let destinationRef = CGImageDestinationCreateWithURL(destinationURL, kUTTypeJPEG, 1, nil) else { return }
// Add image from source to destination with new properties
CGImageDestinationAddImageFromSource(destinationRef, sourceRef, 0, metadata as CFDictionary)
// Save destination
guard CGImageDestinationFinalize(destinationRef) else { return }
guard
let sourceRef2 = CGImageSourceCreateWithURL(destinationURL, nil),
let metadata2 = CGImageSourceCopyPropertiesAtIndex(sourceRef2, 0, nil) else { return }
print("", "saved properties", metadata2, separator:"\n")
}
updateEXIFDateDigitized()
结果的相关位,为了简洁起见,我删除了其他字段:
unmodified properties
{
"{Exif}" = {
DateTimeDigitized = "2007:07:31 17:42:01";
DateTimeOriginal = "2007:07:31 17:42:01";
};
}
modified properties
{
"{Exif}" = {
DateTimeDigitized = "2017-05-11 15:45:38 +0000";
DateTimeOriginal = "2007:07:31 17:42:01";
};
}
saved properties
{
"{Exif}" = {
DateTimeOriginal = "2007:07:31 17:42:01";
};
}