2
我试图修改包含在JPEG图像中的元数据。它可以是图像中的任何元数据,在我的示例中,我试图将DateTimeDigitized
属性更改为当前日期。修改图像元数据
我的代码似乎主要工作,但set属性被删除,而不是改变。我不确定为什么会发生这种情况,谁能告诉我我做错了什么?
我会欢迎任何有助于执行任务的框架建议,但是我特别关心我在这种方法中做错了什么。
我在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, "public.jpeg" as CFString, 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";
};
}
我一直在寻找方法来修改EXIF数据一年,现在,关闭。我在SO上收藏的问题都没有答案。但是今天我做了一次搜索,然后又回来了 - 它并没有说明你实际上可以保存已更改的数据,但它可以帮助你。 http://stackoverflow.com/questions/37992611/swift-how-to-modify-exif-info-in-images-taken-from-mobile-camera让我知道这里,如果它真的有效。 – dfd
@dfd此代码确实能够保存数据,我的数据格式错误,因此它正在被修剪。请参阅我的[answer](http://stackoverflow.com/a/43929720/887210)了解更多信息。 – ColGraff