標籤:style blog io color os ar 使用 for sp
我們在做一些影像處理時,往往會涉及到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行為藍色。
iOS如何將RGB565的原始映像資料轉為UIImage對象