美文网首页图形控件
iOS 图片像素处理

iOS 图片像素处理

作者: Jason_Msbaby | 来源:发表于2016-07-11 18:38 被阅读1581次
    #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 )
    
    //图片颜色渐变
    - (void)imagePifex
    {
        
        // 1. Get the raw pixels of the image
        //定义最高32位整形指针 *inputPixels
        UInt32 * inputPixels;
        
        //转换图片为CGImageRef,获取参数:长宽高,每个像素的字节数(4),每个R的比特数
        CGImageRef inputCGImage = [self.image 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 (int j = 0; j < inputHeight; j++) {
            for (int 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);
                    *currentPixel = RGBAMake(thisR, thisG, thisB, thisA);
                    
         
            }
        }
        //创建新图
        // 4. Create a new UIImage
        CGImageRef newCGImage = CGBitmapContextCreateImage(context);
        UIImage * processedImage = [UIImage imageWithCGImage:newCGImage];
        //释放
        // 5. Cleanup!
        CGColorSpaceRelease(colorSpace);
        CGContextRelease(context);
        free(inputPixels);
        
        self.image = processedImage;
    }
    

    相关文章

      网友评论

        本文标题:iOS 图片像素处理

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