iOS / Objective C:将RGB数据转换为UIImage

我需要帮助将24/32位RGB原始图像转换为uiimage。

我已经从Paul Solt和其他人那里尝试了这些例子,但没有任何工作。 任何人都可以请示例或教程?

图像数据保存在nsdata,我想有一个JPG或PNG图像。

Thx Thorsten

我使用Paul Solt的代码,它做了一些事情,但是图像看起来像是一幅图像中的图像信息的四倍。 我不能在这里发布图像:编辑:我在评论之间的方法开始添加行,现在它的工作原理:-)

+ (UIImage *) convertBitmapRGBA8ToUIImage:(unsigned char *) buffer withWidth:(int) width withHeight:(int) height { // added code char* rgba = (char*)malloc(width*height*4); for(int i=0; i < width*height; ++i) { rgba[4*i] = buffer[3*i]; rgba[4*i+1] = buffer[3*i+1]; rgba[4*i+2] = buffer[3*i+2]; rgba[4*i+3] = 255; } // size_t bufferLength = width * height * 4; CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, rgba, bufferLength, NULL); size_t bitsPerComponent = 8; size_t bitsPerPixel = 32; size_t bytesPerRow = 4 * width; CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); if(colorSpaceRef == NULL) { NSLog(@"Error allocating color space"); CGDataProviderRelease(provider); return nil; } CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; CGImageRef iref = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, // data provider NULL, // decode YES, // should interpolate renderingIntent); uint32_t* pixels = (uint32_t*)malloc(bufferLength); if(pixels == NULL) { NSLog(@"Error: Memory not allocated for bitmap"); CGDataProviderRelease(provider); CGColorSpaceRelease(colorSpaceRef); CGImageRelease(iref); return nil; } CGContextRef context = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, colorSpaceRef, bitmapInfo); if(context == NULL) { NSLog(@"Error context not created"); free(pixels); } UIImage *image = nil; if(context) { CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), iref); CGImageRef imageRef = CGBitmapContextCreateImage(context); // Support both iPad 3.2 and iPhone 4 Retina displays with the correct scale if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) { float scale = [[UIScreen mainScreen] scale]; image = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp]; } else { image = [UIImage imageWithCGImage:imageRef]; } CGImageRelease(imageRef); CGContextRelease(context); } CGColorSpaceRelease(colorSpaceRef); CGImageRelease(iref); CGDataProviderRelease(provider); if(pixels) { free(pixels); } return image; } 

解:

我的位图图像数据只有3个字节,但ios需要4个字节,第四个是alpha。 所以插入下面的代码添加了第4个字节固定的问题。

 char* rgba = (char*)malloc(width*height*4); for(int i=0; i < width*height; ++i) { rgba[4*i] = buffer[3*i]; rgba[4*i+1] = buffer[3*i+1]; rgba[4*i+2] = buffer[3*i+2]; rgba[4*i+3] = 255; } 

这里是NSData到UIImage的转换:

 NSData *imageData = UIImagePNGRepresentation(image); UIImage *image=[UIImage imageWithData:data]; 

我用这个代码创build了PNG图片,希望它也能适合你。