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

来源:互联网 发布:淘宝帐号为什么被冻结 编辑:程序博客网 时间:2024/06/06 04:33

http://www.cnspirit.com/2011/04/uiimage-uiimage.html

生成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;

0 0
原创粉丝点击