Why cgimage.copy always return nil in swift 3?

Eric Chan

My goal is to remove the white background from png image.

First, I used a png has the white background to remove.

Here is my code.

...
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)
...

It works well.

And I edited the image and received the edited image using the bellow code.

...
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)

...

For now, I got the edited image successfully.

Then I added the code which removes white background but I got always nil.

Is there a way to fix this issue?

Eric Smith

The color masking will only work on JPG images unfortunately. See Apple's documentation here:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related