2011年4月16日星期六

uiimage 转换为像素数据 以及从像素数据生成为uiimage

生成RGBABitmapContext 

CGContextRef CreateRGBABitmapContext (CGImageRef inImage){
CGContextRef context = NULL; CGColorSpaceRef colorSpace;
void *bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
size_t pixelsWide = CGImageGetWidth(inImage);
size_t pixelsHigh = CGImageGetHeight(inImage);
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();  if (colorSpace == NULL){
fprintf(stderr, "Error allocating color space");
return NULL;
}

// allocate the bitmap & create context
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL){
printf (stderr, "Memory not allocated!");
CGColorSpaceRelease( colorSpace );
return NULL;
}

context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);

if (context == NULL){
    free (bitmapData);
    fprintf (stderr, "Context not created!");
 }

CGColorSpaceRelease( colorSpace );

 return context;

生成图片的像素数据

// Return Image Pixel data as an RGBA bitmap
unsigned char *RequestImagePixelData(UIImage *inImage) {

CGImageRef img = [inImage CGImage];
CGSize size = [inImage size];
CGContextRef cgctx = CreateRGBABitmapContext(img);
if (cgctx == NULL)
return NULL;

CGRect rect = {{0,0},{size.width, size.height}};
CGContextDrawImage(cgctx, rect, img);
unsigned char *data = CGBitmapContextGetData (cgctx);
CGContextRelease(cgctx);
return data;
}
发表评论