我正在尝试从 unsigned char * 中的原始数据创建一个新图像。我从存储的数据中获得了每像素的位数。 我尝试将原始数据转换为 NSData,但结果图像为零,
unsigned char *bitmap = myData;
NSUInteger myImageDataLength = strlen( (const char*)bitmap);
NSData *d = [NSData dataWithBytes:bitmap length:myImageDataLength];
imgView.image = [UIImage imageWithData:d];
然后我尝试使用上下文创建图像如下:
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
int width = mWidth;
int height = mHeight;
size_t bpp = mBpp;
size_t bpc = 8;
size_t bpr = (width * 4);
CGContextRef context = CGBitmapContextCreate(bitmap, width, height, 8, bpr, colorspace, kCGImageAlphaNone);
CGImageRef cgImage = nil;
if (context != nil) {
cgImage = CGBitmapContextCreateImage (context);
CGContextRelease(context);
}
CGColorSpaceRelease(colorspace);
UIImage *newImage = [UIImage imageWithCGImage:cgImage];
我收到一条错误消息,例如
<强> <Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component color space; kCGImageAlphaNone; 64 bytes/row.
我尝试通过设置许多值来解决它,但找不到任何结果。我在互联网上搜索以找到此解决方案,但所有其他人都在从现有图像创建图像,以便他们获得每个组件的位值等等......我如何从这些数据创建图像???
原始图片:
结果图像:
生成的图像应该被扭曲。 (与 fatBooth 和其他应用程序一样变形)
最佳答案
以下代码从原始像素数据创建一个 UIImage
实例,假设您有:
- pixelData:原始像素数据
- imageWidth, imageHeight:图片尺寸
- scanWidth:每条扫描线的字节数
- bytesPerPixel:每个像素使用的字节数,通常为4
生成的 UIImage
被分配给变量 uiImage
。
CGDataProviderRef provider = CGDataProviderCreateWithData(
NULL,
pixelData,
imageHeight * scanWidth,
NULL);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef imageRef = CGImageCreate(imageWidth,
imageHeight,
8,
bytesPerPixel * 8,
scanWidth,
colorSpaceRef,
bitmapInfo,
provider,
NULL,
NO,
renderingIntent);
UIImage *uiImage = [UIImage imageWithCGImage:imageRef];
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpaceRef);
CGImageRelease(imageRef);
关于iphone - 如何从 unsigned char * 创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7225985/