此代码类型检查并编译,但随后崩溃。如何将CGImage
保存到Data
以便以后可以再次读取。
let cgi: CGImage? = ...
var mData = Data()
let imageDest = CGImageDestinationCreateWithData(mData as! CFMutableData,
kUTTypePNG, 1, nil)!
CGImageDestinationAddImage(imageDest, cgi!, nil)
CGImageDestinationFinalize(imageDest)
最后一行崩溃。控制台中的错误是:
2018-01-17 19:25:43.656664-0500 HelloPencil[2799:3101092] -[_NSZeroData
appendBytes:length:]: unrecognized selector sent to instance 0x1c80029c0
2018-01-17 19:25:43.658420-0500 HelloPencil[2799:3101092] *** Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[_NSZeroData appendBytes:length:]: unrecognized selector
sent to instance 0x1c80029c0'
从Data
到CFMutableData
的演员阵容是Xcode推荐的,但也许是错误的。
问题在于您创建可变数据的方式。 Data
不能直接转换为NSMutableData
。
从Data
转换为CFMutableData
的唯一方法是先将其转换为NSData
,获取其可变副本NSMutableData
并将其转换为CFMutableData
。
NSMutableData
免费电话桥接CFMutableData
但在这种情况下,考虑到您没有要转换的数据,这没有任何意义。只需使用 CFDataCreateMutable(nil, 0)
初始化一个新的 CFMutableData
对象:
if let cgi = cgi,
let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, "public.png" as CFString, 1, nil) {
CGImageDestinationAddImage(destination, cgi, nil)
if CGImageDestinationFinalize(destination) {
let data = mutableData as Data
if let image = UIImage(data: data) {
print(image.size)
}
} else {
print("Error writing Image")
}
}
编辑/更新: Xcode 11 • Swift 5.1
extension CGImage {
var png: Data? {
guard let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, "public.png" as CFString, 1, nil) else { return nil }
CGImageDestinationAddImage(destination, self, nil)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutableData as Data
}
}