Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGImageCreateWithMask works great but the masked out area is black in my resulting image, how can I set it to be white?

I've masked out my image thusly:

    CGImageRef maskRef = [[UIImage imageNamed:@"testMask2.png"] CGImage];

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), nil, YES);

UIImage *image = [UIImage imageWithContentsOfFile:path];

CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);

imageView.image = [UIImage imageWithCGImage:masked];

And it works great, but the resulting image has BLACK where it was masked out, how can I set it to have WHITE where its masked out?

like image 953
Shizam Avatar asked Oct 03 '10 03:10

Shizam


1 Answers

If you are masking JPEG image which does not have alpha channel this will happen (black background instead of transparent).

So you need to do something like this before masking:

    CGImageRef imageNoAlpha = [UIImage imageNamed:@"noAlphaImage.jpg"].CGImage;

CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();

CGFloat width = CGImageGetWidth(imageNoAlpha);
CGFloat height = CGImageGetHeight(imageNoAlpha);

CGContextRef ctxWithAlpha = CGBitmapContextCreate(nil, width, height, 8, 4*width, cs, kCGImageAlphaPremultipliedFirst);

CGContextDrawImage(ctxWithAlpha, CGRectMake(0, 0, width, height), imageNoAlpha);

CGImageRef imageWithAlpha = CGBitmapContextCreateImage(ctxWithAlpha);

CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask);

...

Be sure to release created images, context and colorspace ...

like image 91
Matej Ukmar Avatar answered Oct 19 '22 23:10

Matej Ukmar