我們在做一些圖像處理時,往往會涉及到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分量位於高字節。下面舉個應用例子:
- (void)buttonTouched:(id)sender { unsigned short *imageBuffer = (unsigned short*)malloc(128 * 128 * 2); for(int row = 0; row < 128; row++) { unsigned short color = 0x001f; if(row >= 64) color = 0xf800; for(int col = 0; col < 128; col++) imageBuffer[row * 128 + col] = color; } UIImage *image = [self imageFromRGB565:imageBuffer width:128 height:128]; free(imageBuffer); 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)]; imageView.image = image; [self.view addSubview:imageView]; [imageView release]; }
以上代碼創建了一幅128x128的RGB565的圖像,上64行為紅色;下64行為藍色。