Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

cocoa

uiimage

which is the best way to check whether a UIImage is blank?
I have this painting editor which returns a UIImage; I don't want to save this image if there's nothing on it.

like image 237
nutsmuggler Avatar asked Jan 19 '11 13:01

nutsmuggler


2 Answers

Try this code:

BOOL isImageFlag=[self checkIfImage:image];

And checkIfImage method:

- (BOOL) checkIfImage:(UIImage *)someImage {
    CGImageRef image = someImage.CGImage;
    size_t width = CGImageGetWidth(image);
    size_t height = CGImageGetHeight(image);
    GLubyte * imageData = malloc(width * height * 4);
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * width;
    int bitsPerComponent = 8;
    CGContextRef imageContext =
    CGBitmapContextCreate(
                          imageData, width, height, bitsPerComponent, bytesPerRow, CGImageGetColorSpace(image),
                          kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big
                          );

    CGContextSetBlendMode(imageContext, kCGBlendModeCopy);
    CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
    CGContextRelease(imageContext);

    int byteIndex = 0;

    BOOL imageExist = NO;
    for ( ; byteIndex < width*height*4; byteIndex += 4) {
        CGFloat red = ((GLubyte *)imageData)[byteIndex]/255.0f;
        CGFloat green = ((GLubyte *)imageData)[byteIndex + 1]/255.0f;
        CGFloat blue = ((GLubyte *)imageData)[byteIndex + 2]/255.0f;
        CGFloat alpha = ((GLubyte *)imageData)[byteIndex + 3]/255.0f;
        if( red != 1 || green != 1 || blue != 1 || alpha != 1 ){
            imageExist = YES;
            break;
        }
    }

    free(imageData);        
    return imageExist;
}

You will have to add OpenGLES framework and import this in the .m file:

#import <OpenGLES/ES1/gl.h>
like image 190
Aniket Kote Avatar answered Nov 07 '22 02:11

Aniket Kote


One idea would be to call UIImagePNGRepresentation to get an NSData object then compare it with a pre-defined 'empty' version - ie: call:

- (BOOL)isEqualToData:(NSData *)otherData

to test?

Not tried this on large data; might want to check performance, if your image data is quite large, otherwise if it's small it is probably just like calling memcmp() in C.

like image 2
petert Avatar answered Nov 07 '22 02:11

petert