我正在尝试将EXIF数据写入图像,但 CGImageDestinationFinalize 崩溃:
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
let jpeg = UIImageJPEGRepresentation(image, 1.0)
var source: CGImageSource? = nil
source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
var metadataAsMutable = metadata
var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]
GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 30.21313
GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 76.22346
EXIFDictionary![(kCGImagePropertyExifUserComment as String)] = "Hello Image"
let UTI: CFString = CGImageSourceGetType(source!)!
let dest_data = NSMutableData()
let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
CGImageDestinationFinalize(destination)
答案 0 :(得分:10)
请在下面的答案中查看。 由于 EXIFDictionary 和 GPSDictionary
上的零值,您收到错误 var image = info[UIImagePickerControllerOriginalImage] as! UIImage
let jpeg = UIImageJPEGRepresentation(image, 1.0)
var source: CGImageSource? = nil
source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
var metadataAsMutable = metadata
var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]
if !(EXIFDictionary != nil) {
EXIFDictionary = [AnyHashable: Any]()
}
if !(GPSDictionary != nil) {
GPSDictionary = [AnyHashable: Any]()
}
GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 30.21313
GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 76.22346
EXIFDictionary![(kCGImagePropertyExifUserComment as String)] = "Hello Image"
let UTI: CFString = CGImageSourceGetType(source!)!
let dest_data = NSMutableData()
let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
CGImageDestinationFinalize(destination)
答案 1 :(得分:1)
这可能来自您的目的地定义。
这对我有用
(...)
let source = CGImageSourceCreateWithData(jpgData as CFData, nil)
let finalData = NSMutableData()
let destination = getDestination(finalData:finalData, source:source!)
(...)
// Note that :
// NSMutableData type variable will be cast to CFMutableData
//
fileprivate func getDestination(finalData:CFMutableData, source:CGImageSource)->CGImageDestination?{
guard let destination = CGImageDestinationCreateWithData(finalData,
CGImageSourceGetType(source)!,
1,
nil)else{return nil}
return destination
}