本文介绍了如何在 Swift 中将 CGImage 保存到数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码类型检查并编译但随后崩溃.如何将 CGImage
保存到 Data
以便我以后可以再次读取它.
This code type checks and compiles but then crashes. How do I save a CGImage
to Data
so that I can read it in again later.
let cgi: CGImage? = ...
var mData = Data()
let imageDest = CGImageDestinationCreateWithData(mData as! CFMutableData,
kUTTypePNG, 1, nil)!
CGImageDestinationAddImage(imageDest, cgi!, nil)
CGImageDestinationFinalize(imageDest)
最后一行崩溃了.控制台中的错误是:
The last line crashes. Error in console is:
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 推荐的,但可能是错误的.
That cast from Data
to CFMutableData
was recommended by Xcode, but maybe it's wrong.
推荐答案
问题在于您创建可变数据的方式.只需将您的强制转换从 Data
更改为 CFMutableData
到 CFDataCreateMutable(nil, 0)
The problem is the way you are creating your mutable data. Just change your forced casting from Data
to CFMutableData
to CFDataCreateMutable(nil, 0)
试试这个:
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
}
}
这篇关于如何在 Swift 中将 CGImage 保存到数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!