我的任务是从 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);
我的问题是上面的代码对彩色图像很有用,但对于灰度图像我不知道怎么做。有任何想法吗?