iphone - 如何从 unsigned char * 创建图像

标签 iphone ios image

我正在尝试从 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.

我尝试通过设置许多值来解决它,但找不到任何结果。我在互联网上搜索以找到此解决方案,但所有其他人都在从现有图像创建图像,以便他们获得每个组件的位值等等......我如何从这些数据创建图像???

原始图片:

enter image description here

结果图像:

enter image description here

生成的图像应该被扭曲。 (与 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/

相关文章:

ios - 从 ruby​​ on Rails 应用程序发送文件以在后台打印

css - 在 CakePHP 的 CSS 文件中如何处理 URL,以便它们引用正确的位置?

android - 如何在用户触摸事件时在 xml 布局上 move 图像?

javascript - 有没有办法将视口(viewport)的比例动态重置为 1.0

iphone - 如何垂直移动带有 slider 的 UILabel

javascript - 开 Jest : Error when trying to import Native Modules; unable to prevent with Mock

ios - 白标 iOS 应用程序

java - 在 Java 中将图形与用户界面相结合

iphone - 从应用程序打开/关闭 iPhone 的 Wifi

iphone - iOs5,试图了解 UIPickerView 以及如何将它连接到我的自定义类