为什么cgimage.copy总是在swift 3中返回nil?

时间:2017-01-10 04:00:41

标签: image-processing swift3

我的目标是从png图像中删除白色背景。

首先,我使用png有白色背景去除。

这是我的代码。

...
let imageRef = self.imageView.image?.cgImage?.copy(maskingColorComponents:[222,255,222,255,222,255,222,255])
self.imageView.image = UIImage(cgImage: imageRef, scale: self.imageView.image?.scale, orientation: self.imageView.image.imageOrientation)
...

效果很好。

我编辑了图像并使用波纹管代码接收了编辑过的图像。

...
UIGraphicsBeginImageContext(self.imageView.image.frame.size)
self.imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageRef = self.imageView.image?.cgImage?.copy(maskingColorComponents:[222,255,222,255,222,255,222,255])
// imageRef is always nil ???
self.imageView.image = UIImage(cgImage: imageRef, scale: self.imageView.image?.scale, orientation: self.imageView.image.imageOrientation)

...

目前,我已成功修改了已编辑的图像。

然后我添加了删除白色背景的代码,但我总是没有。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

不幸的是,彩色遮罩仅适用于JPG图像。请参阅Apple的文档:

https://developer.apple.com/reference/coregraphics/1454358-cgimagecreatewithmaskingcolors