0

I am using following code to save uiimage. Before saving the image, i want to check the image is empty or blank.

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();

Note :

UIImage, check if contain image How to check if a uiimage is blank? (empty, transparent)

I couldn't find solution in the above link. Thanks!!!

Community
  • 1
  • 1
Samy
  • 23
  • 4

1 Answers1

2

I found a solution for the above problem. This may help anyone in future. This below function works perfectly for even PNG transparent image.

-(BOOL)isBlankImage:(UIImage *)myImage
{
typedef struct
{
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    uint8_t alpha;
} MyPixel_T;

CGImageRef myCGImage = [myImage CGImage];

//Get a bitmap context for the image
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(myCGImage), CGImageGetHeight(myCGImage),
                      CGImageGetBitsPerComponent(myCGImage), CGImageGetBytesPerRow(myCGImage),
                      CGImageGetColorSpace(myCGImage), CGImageGetBitmapInfo(myCGImage));

//Draw the image into the context
CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(myCGImage), CGImageGetHeight(myCGImage)), myCGImage);

//Get pixel data for the image
MyPixel_T *pixels = CGBitmapContextGetData(bitmapContext);
size_t pixelCount = CGImageGetWidth(myCGImage) * CGImageGetHeight(myCGImage);
for(size_t i = 0; i < pixelCount; i++)
{
    MyPixel_T p = pixels[i];
    //Your definition of what's blank may differ from mine
    if(p.red > 0 || p.green > 0 || p.blue > 0 || p.alpha > 0)
        return NO;
}

return YES;
}
Samy
  • 23
  • 4