繁体   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