字节数组到UIImage Objective-C [英] Byte Array to UIImage Objective-C

查看:64
本文介绍了字节数组到UIImage Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组

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.这是如何运作的?我尝试过:

Now I want to convert this Data to an UIImage. How does that work? I've tried:

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

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

But this doesn't seem to be the right solution. Please help.

推荐答案

    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);

这篇关于字节数组到UIImage Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆