【问题标题】:Byte Array to UIImage Objective-C字节数组到 UIImage Objective-C
【发布时间】:2011-07-12 06:51:31
【问题描述】:

我有一个字节数组

unsigned char *outputData = (unsigned char *)malloc(sizeof(unsigned char) * w * h * 4);

    outputData[y * h * 4 + x * 4 + 0] = all; //alpha value
    outputData[y * h * 4 + x * 4 + 1] = red; //red value
    outputData[y * h * 4 + x * 4 + 2] = gre; //green value
    outputData[y * h * 4 + x * 4 + 3] = blu; //blue value

            //h... total image height
            //y,x ... current y and x value from the matrix

现在我想将此数据转换为 UIImage。这是如何运作的?我试过了:

NSData *outdata = [NSData dataWithBytes:outputData length:sizeof(unsigned char) * w * h * 4];
UIImage *newimage = [UIImage imageWithData:outdata];

但这似乎不是正确的解决方案。请帮忙。

【问题讨论】:

  • 好吧,我想我解决了。我发现 imageWithData 只是在创建格式为 (png, jpeg) 的图像。所以我需要先创建一个上下文,对吧?

标签: iphone objective-c uiimage bytearray


【解决方案1】:
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext=CGBitmapContextCreate(outputData, w, h, 8, 4*w, colorSpace,  kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
    CFRelease(colorSpace);
    free(outputData);
    CGImageRef cgImage=CGBitmapContextCreateImage(bitmapContext);
    CGContextRelease(bitmapContext);

    UIImage * newimage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);

【讨论】:

  • 非常感谢。工作完美。 (只需将 kCGImageAlphaPremultipliedLast 更改为 kCGImageAlphaPremultipliedFirst)
  • 请将此答案标记为正确答案,因为它有效;)
  • 如果您需要 BGRA 转换,请使用kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Little 代替位图信息。
猜你喜欢
  • 2011-11-09
  • 2017-01-06
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
相关资源
最近更新 更多