iOS小Demo之获取图片像素数据

#define R(x) ( Mask8(x) )

#define G(x) ( Mask8(x >> 8 ) )

#define B(x) ( Mask8(x >> 16) )

-(void)getImagePixel

{

    UIImage *baseImage = [UIImage imageNamed:@"base"];

    CGImageRef inputCGImage = [baseImage CGImage];

    NSUInteger width = CGImageGetWidth(inputCGImage);

    NSUInteger height = CGImageGetHeight(inputCGImage);

    NSUInteger bytesPerPixel = 4;

    NSUInteger bytesPerRow = bytesPerPixel *width;

    NSUInteger bitsPerComponent = 8;

    UInt32 * pixels;

    pixels = (UInt32 *)calloc(height * width, sizeof(UInt32));

    CGColorSpaceRef colorSpace =  CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(pixels, width, height,bitsPerComponent, bytesPerRow, colorSpace,kCGImageAlphaPremultipliedLast |     kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0,0, width, height), inputCGImage);

    CGColorSpaceRelease(colorSpace);

    CGContextRelease(context);

    

    UInt32 * currentPixel = pixels;

    for (NSUInteger j = 0; j < height; j++) {

        for (NSUInteger i = 0; i < width; i++) {

            UInt32 color = *currentPixel;

            printf("%d", ((R(color)+G(color)+B(color))/3.0 == 255)?0:1);

            currentPixel++;

        }

        printf("\n");

    }

}

你可能感兴趣的:(iOS小Demo之获取图片像素数据)