-
Make UIImage White Background Transparent in iOS
over 9 years ago
-
almost 9 years ago
Hello this is great code! Can you provide a Seift 2.0 version?
-
-
almost 9 years ago
extension UIImage {
func imageByMakingWhiteBackgroundTransparent() -> UIImage? { if let rawImageRef = self.CGImage { let colorMasking: [CGFloat] = [200, 255, 200, 255, 200, 255] UIGraphicsBeginImageContext(self.size) if let maskedImageRef = CGImageCreateWithMaskingColors(rawImageRef, colorMasking) { CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, self.size.height) CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0) CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height), maskedImageRef) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } } return nil }
}
-
-
almost 7 years ago
Hi
I am not getting the proper result that i want by this code please help.
Thanks -
-
over 8 years ago
A. The code of *CGImageCreateWithMaskingColors* returns nil, probably when trying to handle an image with alpha channel. Can someone know how we can bypass this?
And for anyone asking - Swift 2.0 code of the extension:
extension UIImage {
func imageByMakingWhiteBackgroundTransparent() -> UIImage? { if let rawImageRef = self.CGImage { //TODO: eliminate alpha channel if exsists let colorMasking: [CGFloat] = [200, 255, 200, 255, 200, 255] UIGraphicsBeginImageContext(self.size) if let maskedImageRef = CGImageCreateWithMaskingColors(rawImageRef, colorMasking) { CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, self.size.height) CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0) CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height), maskedImageRef) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } } return nil }
}
-
4 Comment(s)