我试图使用以下代码将图像保存到iPhone上的用户相机胶卷:
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
但是尽管没有崩溃或发生错误,但它失败了。我确保图像是有效的(不是零)UIImage,它确实如此。所以我尝试实现完成处理程序,如下所示:
UIImageWriteToSavedPhotosAlbum(uiImage, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
// ....
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if error != nil {
print("ERROR! ", error!.localizedDescription)
}
}
但这仍然没有给我一个错误。最后,我尝试在模拟器上运行。这给了我以下错误:
Connection to assetsd was interrupted or assetsd died
Error! Write failed
导致此失败的原因是什么?
答案 0 :(得分:5)
我遇到了this link,其中说为了运行UIImageWriteToSavedPhotosAlbum
,UIImage"必须是CGImage支持的"。因此,为了解决这个问题,我编写了以下代码将我的UIImage转换为CIImage,然后转换为CGImage,然后返回到UIImage:
let ciImage = self.image!.ciImage
let context = CIContext()
let cgImage = context.createCGImage(ciImage!, from: ciImage!.extent)
let uiImage = UIImage(cgImage: cgImage!)
UIImageWriteToSavedPhotosAlbum(uiImage, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
这终于工作并按照预期保存到相机胶卷!