【问题标题】:How to check uiimage is empty or blank如何检查uiimage是否为空或空白
【发布时间】:2026-01-27 06:00:01
【问题描述】:

我正在使用以下代码来保存 uiimage。在保存图像之前,我想检查图像是空的还是空白的。

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

注意:

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

我在上面的链接中找不到解决方案。谢谢!!!

【问题讨论】:

    标签: uiimage cgcontext


    【解决方案1】:

    我找到了解决上述问题的方法。这可能对将来的任何人都有帮助。下面的这个函数甚至可以完美地适用于 PNG 透明图像。

    -(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;
    }
    

    【讨论】: