views:

198

answers:

2

Hi there,

I have a UIImage with white background. I would like replace the white background/pixels with alpha-transparent pixels. I've looked at other questions on StackOverflow, along with Quartz documentation, but have yet to find a coherent "start-to-end" for this problem. How is this done?

+1  A: 

The first step is you need to define some sort of "distance" function to determine how far away a pixel is from being white. Then you need to define a distance threshold below which a pixel is considered white. Then you would need to iterate over the pixels of the image, changing any pixels that were considered white according to your distance and threshold, to being transparent. The main trick, though, is making this efficient... touching pixels through functions will be very slow; your best bet is to touch the pixels directl by gaining access to the memory buffer in which the pixels reside and stepping through them.

Michael Aaron Safyan
Do you know of functions that can do this within iPhone OS? I don't know if direct memory buffer access is even possible...
Peter Hajas
@Peter, sorry, not really... my own approach would be to send the image to a web service, process it on the web service, and then return the image. Anything that is going to do image processing is going to be fairly computationally intensive and not so great for battery life.
Michael Aaron Safyan
+2  A: 
CGImageCreateWithMaskingColors

A UIImage wraps a CGImage. Take the CGImage, run it through CGImageCreateWithMaskingColors, then either create a new UIImage from the result or assign the result back to the UIImage.

drawnonward
Thanks for this! I am slightly confused about the parameters for the function, particularly the "components" array. What are the proper CGFloat values to fill this with? The documentation mentions floating-point pixel components vs integer pixel components. How do I determine this, and which values represent white?Thanks again!
Peter Hajas
It all depends on the image. The most likely white would be 255,255,255 for an rgb png or jpg. You can use `CGImageGetBitmapInfo`, `CGImageGetBitsPerPixel` and `CGImageGetBitsPerComponent` to figure out more.
drawnonward
Many many thanks for your help! This was great!For future people, I used:{0xEE, 0xFF, 0xEE, 0xFF, 0xEE, 0xFF}Hex, it's what's for dinner.
Peter Hajas