如何迭代ARGB位图?

时间:2010-10-31 00:15:37

标签: objective-c image-processing ios4

我有点困惑。我有一个ARGB位图到unsigned char*数组,我只是想迭代数组来检查像素是黑色还是白色。有人可以给我发一个示例代码吗?

要获取数组,我正在使用此方法。

CGContextRef CreateARGBBitmapContext (CGSize size) {

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }

    void *bitmapData = malloc(size.width * size.height * 4);
    if (bitmapData == NULL)
    {
        fprintf (stderr, "Error: Memory not allocated!");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }

    CGContextRef context = CGBitmapContextCreate (bitmapData, size.width, size.height, 8, size.width * 4, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGColorSpaceRelease(colorSpace );
    if (context == NULL)
    {
        fprintf (stderr, "Error: Context not created!");
        free (bitmapData);
        return NULL;
    }

    return context;
}

- (unsigned char *)bitmapFromImage:(UIImage *)image {

    //Create a bitmap for the given image.
    CGContextRef contex = CreateARGBBitmapContext(image.size);
    if (contex == NULL) {
        return NULL;
    }

    CGRect rect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
    CGContextDrawImage(contex, rect, image.CGImage);
    unsigned char *data = CGBitmapContextGetData(contex);
    CGContextRelease(contex);
    return data;
}

为了测试所有,我正在使用它。

- (void)viewDidLoad {

    [super viewDidLoad];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"verticalLine320x460" ofType:@"png"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];

    unsigned char *imageBitmap = (unsigned char *)[self bitmapFromImage:image];

    [image release];
}

感谢您阅读。

2 个答案:

答案 0 :(得分:1)

你的意思是,只是:

typedef struct argb_s {
 unsigned char a;
 unsigned char r;
 unsigned char g;
 unsigned char b;
} argb_t;

argb_t argb = (argb_t *) bitmapData;
for (i=0;i<size.width * size.height;i++) {
  if ((!argb[i].r) && (!argb[i].g) && (!argb[i].b)) 
    NSLog(@"%d,%d is black",(i%size.width),(i/size.height));
}

答案 1 :(得分:0)

无论如何,我在这里让自己的解决方案。

for (i=0; i<image.size.width * image.size.height * 4; i++) {

        // Gets the real position into the bitmap, grouping the a, the r, the g and the b component.
        int aux = (int) i / 4;
        // Shows the r, the g and the b component. Like this you can check the color.
        NSLog(@"%d, %d, %d - R", (aux % width + 1), ((int)(aux / width) + 1), dataBitmap[i+1]);
        NSLog(@"%d, %d, %d - G", (aux % width + 1), ((int)(aux / width) + 1), dataBitmap[i+2]);
        NSLog(@"%d, %d, %d - B", (aux % width + 1), ((int)(aux / width) + 1), dataBitmap[i+3]);
}

感谢阅读。