美文网首页
iOS校验图片每个像素透明度

iOS校验图片每个像素透明度

作者: ONE2 | 来源:发表于2022-03-04 10:04 被阅读0次
    
    - (void)canAsNightClubBodyImage:(void(^)(BOOL can))finish {
        CGImageRef imgref = self.CGImage;
    
        //   获取图片宽高(总像素数)
        size_t width = CGImageGetWidth(imgref);
        size_t height = CGImageGetHeight(imgref);
        // 每行像素的总字节数
        size_t bytesPerRow = CGImageGetBytesPerRow(imgref);
        // 每个像素多少位(RGBA每个8位,所以这里是32位)         ps:(一个字节8位)
        size_t bitsPerPixel = CGImageGetBitsPerPixel(imgref);
        CGDataProviderRef dataProvider = CGImageGetDataProvider(imgref);
        CFDataRef data = CGDataProviderCopyData(dataProvider);
    
        UInt8 *buffer = (UInt8*)CFDataGetBytePtr(data);// 图片数据的首地址
        
        int area = 24;
        int total = 0;
        int alphaZero = 0;
        // left top
        for (int x = 0; x < area; x ++ ) {
            for (int y = 0; y < area; y ++) {
                total ++;
                //每个像素的首地址
                UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
    //            UInt8  red = *pt;
    //            UInt8  green = *(pt+1);   //指针向后移动一个字节
    //            UInt8  blue = *(pt+2);
                UInt8  alpha = *(pt+3);
                if (alpha < 0.1) {
                    alphaZero ++;
                }
            }
        }
        // left bottom
        for (int x = 0; x < area; x ++ ) {
            for (long y = height - area; y < height; y ++) {
                total ++;
                UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
                UInt8  alpha = *(pt+3);
                if (alpha < 0.1) {
                    alphaZero ++;
                }
            }
        }
        // right top
        for (long x = width - area; x < width; x ++ ) {
            for (int y = 0; y < area; y ++) {
                total ++;
                UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
                UInt8  alpha = *(pt+3);
                if (alpha < 0.1) {
                    alphaZero ++;
                }
            }
        }
        // right bottom
        for (long x = width - area; x < width; x ++ ) {
            for (long y = height - area; y < height; y ++) {
                total ++;
                UInt8 *pt = buffer + y * bytesPerRow + x * (bitsPerPixel/8);
                UInt8  alpha = *(pt+3);
                if (alpha < 0.1) {
                    alphaZero ++;
                }
            }
        }
        
        // 有这行会崩溃 CGDataProviderRelease(dataProvider);
        
        float percent = alphaZero*1.0/total;
        finish(percent > 0.2);
    }
    
    

    相关文章

      网友评论

          本文标题:iOS校验图片每个像素透明度

          本文链接:https://www.haomeiwen.com/subject/epiprrtx.html