簡體   English   中英

通過 CGBitmapContextCreate 獲取像素 RGB 錯誤

[英]Get pixel RGB wrong by CGBitmapContextCreate

我遇到了一個奇怪的問題。 我使用 CGBitmapContextCreate 從圖像中獲取原始像素數據,然后修改指定位置的像素顏色。 但是,我發現當我獲得 alpha 等於 1 的像素的 RGBA 時,一切正常,但是如果 alpha 小於 1,則 RGB 是錯誤的,它的顏色更深。 誰能告訴我為什么,它讓我發瘋......

這是我的代碼,你可以在這里得到測試圖片

圖片

#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)getPixelRGBA
{
    UIImage *image = [UIImage imageNamed:@"testpicture.png"];
    NSUInteger bytesPerRow = 4*image.size.width;
    UInt32 *pixels = (UInt32 *)calloc(image.size.width*image.size.height, sizeof(UInt32));

    CGContextRef context = CGBitmapContextCreate(pixels, image.size.width, image.size.height, 8, bytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);

    // pixel with alpha < 1, color gets dark
    int offset1 = 75 * (int)image.size.width + 75;
    UInt32 *pixelValue1 = pixels + offset1;
    UInt32 pixelColor1 = *pixelValue1;
    UInt32 r1 = R(pixelColor1);
    UInt32 g1 = G(pixelColor1);
    UInt32 b1 = B(pixelColor1);
    CGFloat a1 = A(pixelColor1)/255.0f;

    // pixel with alpha == 1, color is right
    int offset2 = 75 * (int)image.size.width + 80;
    UInt32 *pixelValue2 = pixels + offset2;
    UInt32 pixelColor2 = *pixelValue2;
    UInt32 r2 = R(pixelColor2);
    UInt32 g2 = G(pixelColor2);
    UInt32 b2 = B(pixelColor2);
    CGFloat a2 = A(pixelColor2)/255.0f;
}

非常感謝你們!

iOS 使用預乘 alpha (這是Premultiplied的一部分kCGImageAlphaPremultipliedLast )。

這意味着一個像素的 R、G 和 B 通道的范圍不是 0 ... 255。它們的范圍是 0 ... A。如果 R 通道是 127,但 A 通道也是 127,那么那R 處於全強度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM