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

后端 未结 6 2077
说谎
说谎 2020-12-31 23:07

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 imag

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 23:11

    I'm not at my Mac, so I can't test this (and there are probably compile errors). But one method might be:

    //The pixel format depends on what sort of image you're expecting. If it's RGBA, this should work
    typedef struct
    {
       uint8_t red;
       uint8_t green;
       uint8_t blue;
       uint8_t alpha;
    } MyPixel_T;
    
    UIImage *myImage = [self doTheThingToGetTheImage];
    CGImageRef myCGImage = [myImage CGImage];
    
    //Get a bitmap context for the image
    CGBitmapContextRef *bitmapContext = 
    CGBitmapContextFreate(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;
    

提交回复
热议问题