我们在做一些图像处理时,往往会涉及到RGB565这种图像数据格式。由于其每个像素仅占2个字节,对于不需要像素透明度的情况下使用RGB565既能基本能保证图像的色彩,又能降低图像数据尺寸,节省带宽。因此,RGB565将会是一种常用的比较经济的图像处理的格式。
下面就来描述一下如何在iOS中将一段RGB565的原始图像数据转为UIImage对象。见以下代码:
- (UIImage*)imageFromRGB565:(void*)rawData width:(int)width height:(int)height { const size_t bufferLength = width * height * 2; NSData *data = [NSData dataWithBytes:rawData length:bufferLength]; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data); // Creating CGImage from cv::Mat CGImageRef imageRef = CGImageCreate(width, //width height, //height 5, //bits per component 16, //bits per pixel width * 2, //bytesPerRow colorSpace, //colorspace kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder16Little,// bitmap info provider, //CGDataProviderRef NULL, //decode false, //should interpolate kCGRenderingIntentDefault //intent ); // Getting UIImage from CGImage UIImage *finalImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); CGDataProviderRelease(provider); CGColorSpaceRelease(colorSpace); return finalImage; }
iOS中,QuartzCore支持的16位RGB就一种格式——AlphaNoneSkipFirst,每个分量5比特,每个像素16比特,字节序为ByteOrder16Little。因此,R分量位于低字节;而B分量位于高字节。下面举个应用例子:
1 - (void)buttonTouched:(id)sender 2 { 3 unsigned short *imageBuffer = (unsigned short*)malloc(128 * 128 * 2); 4 for(int row = 0; row < 128; row++) 5 { 6 unsigned short color = 0x001f; 7 if(row >= 64) 8 color = 0xf800; 9 10 for(int col = 0; col < 128; col++) 11 imageBuffer[row * 128 + col] = color; 12 } 13 14 UIImage *image = [self imageFromRGB565:imageBuffer width:128 height:128]; 15 free(imageBuffer); 16 17 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 128.0f) * 0.5f, (self.view.frame.size.height - 128.0f) * 0.5f, 128.0f, 128.0f)]; 18 imageView.image = image; 19 [self.view addSubview:imageView]; 20 [imageView release]; 21 }
以上代码创建了一幅128x128的RGB565的图像,上64行为红色;下64行为蓝色。