首页 > 移动平台 > 详细

[iOS 使用CGImage获取并修改图片像素]

时间:2015-03-21 13:48:55      阅读:3535      评论:0      收藏:0      [点我收藏+]
#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )
#define A(x) ( Mask8(x >> 24) )
#define RGBAMake(r, g, b, a) ( Mask8(r) | Mask8(g) << 8 | Mask8(b) << 16 | Mask8(a) << 24 )

- (UIImage *)processUsingPixels:(UIImage*)inputImage {
    // 1. Get the raw pixels of the image
    //定义最高32位整形指针 *inputPixels
    UInt32 * inputPixels;
    
    //转换图片为CGImageRef,获取参数:长宽高,每个像素的字节数(4),每个R的比特数
    CGImageRef inputCGImage = [inputImage CGImage];
    NSUInteger inputWidth = CGImageGetWidth(inputCGImage);
    NSUInteger inputHeight = CGImageGetHeight(inputCGImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    NSUInteger bytesPerPixel = 4;
    NSUInteger bitsPerComponent = 8;
    
    //每行字节数
    NSUInteger inputBytesPerRow = bytesPerPixel * inputWidth;
    
    //开辟内存区域,指向首像素地址
    inputPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32));
    
    //根据指针,前面的参数,创建像素层
    CGContextRef context = CGBitmapContextCreate(inputPixels, inputWidth, inputHeight,
                                                 bitsPerComponent, inputBytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    //根据目前像素在界面绘制图像
    CGContextDrawImage(context, CGRectMake(0, 0, inputWidth, inputHeight), inputCGImage);
    
    //接来下就是重点了!!!像素处理--------------------------------------------------------
    for (NSUInteger j = 0; j < inputHeight; j++) {
        for (NSUInteger i = 0; i < inputWidth; i++) {
            UInt32 * currentPixel = inputPixels + (j * inputWidth) + i;
            UInt32 color = *currentPixel;
                    UInt32 br,thisR,thisG,thisB,thisA;
                    //这里直接移位获得RBGA的值,以及输出写的非常好!
                     thisR=R(color);
                     thisG=G(color);
                     thisB=B(color);
                     thisA=A(color);
                    //NSLog(@"%d,%d,%d,%d",thisR,thisG,thisB,thisA);
                    br=B(color)-R(color);
                    *currentPixel = RGBAMake(br, br, br, A(color));
        }
    }
    //创建新图
    // 4. Create a new UIImage
    CGImageRef newCGImage = CGBitmapContextCreateImage(context);
    UIImage * processedImage = [UIImage imageWithCGImage:newCGImage];
    //释放
    // 5. Cleanup!
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    free(inputPixels);
    
    return processedImage;
}

 

[iOS 使用CGImage获取并修改图片像素]

原文:http://www.cnblogs.com/rayshen/p/4355403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!