How to mask UIImage so that white becomes transparent on iphone?

I have a UIImage (generated by a custom pattern) that has a white background. I would like to make the white parts of this image transparent. I would also like to save this as a PNG file.

I looked through the forums, but I can’t figure out how to properly mask the image. Has anyone tried this before?

Thank.

+2
source share
3 answers

Try something like this ...

CGImageRef myMaskedImage = [myImage CGImage];
const float whiteMask[6] = { 255,255,255, 255,255,255 };
CGImageRef myColorMaskedImage = CGImageCreateWithMaskingColors(image, whiteMask);

CGDataProviderRef provider;
CGImageRef myPngImage = CGImageCreateWithPNGDataProvider(provider, NULL, true, kCGRenderingIntentDefault);

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt: 72], kCGImagePropertyDPIHeight, [NSNumber numberWithInt: 72], kCGImagePropertyDPIWidth, nil];
CGImageDestinationRef destRef = CGImageDestinationCreateWithURL ((CFURLRef)outPath, (CFStringRef)@"image.png" , 1, NULL);
CGImageDestinationAddImage(destRef, myPngImage, (CFDictionaryRef)options);
CGImageDestinationFinalize(destRef);
CGRelease(destRef);

CGImageRelease(myColorMaskedImage);
CGImageRelease(myPngImage);

from a rather long winding Quartz2d Programming Guide and this mailing list .

+3
source

UIImage, UIImageView, .

0

You will need to get the raw data, look for white pixels, change the alpha of these pixels and save them in a new NSData object, and then convert them to PNG.

It is not difficult, but I would not call it trivial.

0
source

All Articles