views:

30

answers:

2

Hi to all.

I am a bit confused. I have an ARGB bitmap into an unsigned char* array and I just want to iterate the array to check if pixels are black or white. Can anyone post me a sample code for this?

To get the array I am using this methods.

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;
}

To test all, I am using this.

- (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];
}

Thanks for read.

+1  A: 

You mean, just:

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));
}
Brad