Hitarth Hitarth - 1 year ago 118
Objective-C Question

Issue in checking UIImage have alpha (Transparant) color or not

hi i m checking that image have transparent area (alpha) or not. Bashed on that i have to change the color of


I have implement the below method to check the image have
or not.

- (BOOL) checkAlpha : (UIImage*) image
for(int x = 0; x < image.size.width ; x++)
for(int y = 0; y < image.size. height; y++)
CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
const UInt8* data = CFDataGetBytePtr(pixelData);

int pixelInfo = ((image.size.width * y) + x ) * 4; // The image is png

UInt8 red = data[pixelInfo]; // If you need this info, enable it
UInt8 green = data[(pixelInfo + 1)]; // If you need this info, enable it
UInt8 blue = data[pixelInfo + 2]; // If you need this info, enable it
UInt8 alpha = data[pixelInfo + 3]; // I need only this info for my maze game

UIColor* color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f];

DLog(@"color : %@",color);
DLog(@"alpha : %hhu",alpha)

if (alpha)
return YES; // display original image from url.
return NO; // apply brand color here.
return YES;

This method is working fine but for some image it is creating issue.
See the below image

enter image description here
For this image alpha return 0;

enter image description here
enter image description here
And For above 2 images alpha have some value.

All 3 images have same white background.
For the first image also should have some alpha. it should not be 0.
Please guide me out on this ? is there any code error in my method or what?

Answer Source

Finally find out the solution for the current images which are displaying on the question. I want to find out that UIImage have alpha Channel or not.

- (BOOL) hasAlphaChannel  : (UIImage*) image
    if ([self hasAlpha:image])
        return YES;
    return NO;

- (BOOL)hasAlpha : (UIImage*) img
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(img.CGImage);
    return (
            alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast


This hasAlpha method is working fine in this case.

For More info : Check out this link

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download