iOS 圖片像素處理

#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;
    
    //轉(zhuǎn)換圖片為CGImageRef,獲取參數(shù):長寬高,每個像素的字節(jié)數(shù)(4),每個R的比特數(shù)
    CGImageRef inputCGImage = [self.image CGImage];
    NSUInteger inputWidth = CGImageGetWidth(inputCGImage);
    NSUInteger inputHeight = CGImageGetHeight(inputCGImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    NSUInteger bytesPerPixel = 4;
    NSUInteger bitsPerComponent = 8;
    
    //每行字節(jié)數(shù)
    NSUInteger inputBytesPerRow = bytesPerPixel * inputWidth;
    
    //開辟內(nèi)存區(qū)域,指向首像素地址
    inputPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32));
    
    //根據(jù)指針,前面的參數(shù),創(chuàng)建像素層
    CGContextRef context = CGBitmapContextCreate(inputPixels, inputWidth, inputHeight,
                                                 bitsPerComponent, inputBytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    //根據(jù)目前像素在界面繪制圖像
    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);
                
     
        }
    }
    //創(chuàng)建新圖
    // 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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容