判断一个图片是不是纯色

2019-08-27  本文已影响0人  车在路上爬fly
BOOL isPureColor = [self judgePureColor:self.resultImage]; //判断是否是纯色图片

#pragma mark --- 判断是否是一个纯色图片
/**
 判断是否是一个纯色图片
 @param image 目标图片
 @return 返回值
 */
-(BOOL)judgePureColor:(UIImage*)image{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(40, 40);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    
    if (data == NULL) return YES;
    
    int temp_r =  data[0],temp_g = data[1],temp_b = data[2];
    
    BOOL flag = NO;
    for (int x=0; x<thumbSize.width*thumbSize.height; x++) {
        
        int offset = 4*x;
        int red = data[offset];
        int green = data[offset+1];
        int blue = data[offset+2];
        //        int alpha =  data[offset+3];
        //
        //        NSLog(@"r == %d",red);
        //        NSLog(@"g == %d",green);
        //        NSLog(@"b == %d",blue);
        
        if (red == temp_r && green == temp_g && temp_b == blue) {
            //颜色相同仍然继续
            flag = YES;
        }else{
            //颜色不同---停止
            flag = NO;
            break;
        }
        temp_r = red;
        temp_g = green;
        temp_b = blue;
    }
    CGContextRelease(context);
    
    return flag;
}
上一篇下一篇

猜你喜欢

热点阅读