views:

1272

answers:

3

Hi All,

I have a UIImage (generated by a user drawing) that has a white background. I'd like to make the white portions of this image transparent. I'd also like to save this to a PNG file.

I've looked around on forums but can't figure out how to mask the image correctly. Has anyone tried this before?

Thanks.

A: 

You could try making the starting UIImage completely transparent and then have another UIImageView behind it that is completely white.

Tozar
A: 

You're going to have to get at the raw data, look for white pixels, modify the alpha of those pixels and save to a new NSData object and then convert that to a PNG.

It's not difficult, but I wouldn't call it trivial.

Kailoa Kadano
A: 

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 the rather long winded Quartz2d Programming Guide and this mailing list message.

slf