2010-10-31 30 views
1

我有點困惑。我有一個ARGB位圖到unsigned char*數組中,我只是想迭代數組來檢查像素是黑色還是白色。任何人都可以給我發一個這樣的示例代碼嗎?如何迭代ARGB位圖?

爲了得到數組,我使用了這種方法。

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

感謝您的閱讀。

回答

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)); 
} 
+0

謝謝布拉德。你的解決方案工作正常 – 2010-11-01 19:59:52

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

感謝您的閱讀。