从UIImage获取不支持格式的像素数据?

时间:2011-05-08 19:02:38

标签: ios iphone uiimage pixel

作为this question的特例:

如果您的UIImage格式不受支持,您会怎么做?在我的例子中,我有一个单色的UIImage对象,我从一个文件读入。每个像素具有8位颜色(白色)数据,后跟8位alpha数据。格式不受支持,但图像在iPhone屏幕上显示正常。

但是,如引用的问题中所述获取像素数据将不起作用,因为格式不受支持。那我该怎么办?

2 个答案:

答案 0 :(得分:0)

这样的事情会起作用,实质上是将图像转换为单色位图来操纵像素数据。

   CGImageRef cgImage = [image CGImage];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(cgImage), CGImageGetHeight(cgImage), 8, CGImageGetWidth(cgImage)*2, colorSpace, kCGImageAlphaLast);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGBitmapContextGetWidth(bitmapContext), CGBitmapContextGetHeight(bitmapContext)), cgImage);

    UInt8 *data = CGBitmapContextGetData(bitmapContext);
    int numComponents = 2;
    int bytesInContext = CGBitmapContextGetHeight(bitmapContext) * CGBitmapContextGetBytesPerRow(bitmapContext);

    int white;
    int alpha;


    for (int i=0; i < bytesInContext; i+= numComponents) {

        white = data[i];
        alpha = data[i+1];
    }

答案 1 :(得分:0)

您必须渲染为已知/支持的像素格式。只需设置一个灰度或24BPP的位图渲染目标,然后以1:1的宽高比将图像绘制到像素缓冲区中,这样就不会调整大小。然后将已知格式结果检查为字节或字大小的像素。你只需要担心iOS上的sRGB色彩空间,这样可以保持简单,你可以直接从像素缓冲区中读取像素值。