我的任務是從UIImage對象中獲取所有圖像像素,然後將它們存儲在變量中。對我來說,做到這一點的彩色圖像由此不難:如何從UIImage對象中獲取所有圖像像素
CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
size_t ele = CGColorSpaceGetNumberOfComponents(colorSpace);
CGFloat cols = image.size.width;
CGFloat rows = image.size.height;
// Create memory for the input image
unsigned char *img_mem;
img_mem = (unsigned char*) malloc(rows*cols*4);
unsigned char *my_img;
my_img = (unsigned char *)malloc(rows*cols*3);
CGContextRef contextRef = CGBitmapContextCreate(img_mem, cols, // Width of bitmap
rows, // Height of bitmap
8, // Bits per component
cols*4, // Bytes per row
colorSpace, // Colorspace
kCGImageAlphaNoneSkipLast|kCGBitmapByteOrderDefault); // Bitmap info flags
CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);
unsigned int pos_new;
unsigned int pos_old;
for(int i=0; i<rows; i++)
{
pos_new = i*cols*3;
pos_old = i*cols*4;
for(int j=0; j<cols; j++)
{
my_img[j*3+pos_new] = img_mem[pos_old+j*4];
my_img[j*3+pos_new+1] = img_mem[pos_old+j*4+1];
my_img[j*3+pos_new+2] = img_mem[pos_old+j*4+2];
}
}
free(img_mem);
//All the pixels are installed in my_img
free(my_img);
我的問題是上面的代碼是彩色圖像是有用的,但對於灰度圖像,我不如何做到這一點。有任何想法嗎?
你能否舉一個例子來說明我們需要動態地做到這一點的情況?謝謝。 – Unheilig