如何在 Swift 中将 CGImage 保存到数据



此代码类型检查并编译,但随后崩溃。如何将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'

DataCFMutableData的演员阵容是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
    }
}

最新更新