字节数组到UIImage Objective-C

Mar*_*rco 2 iphone bytearray objective-c uiimage

我有一个Bytearray

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

Ila*_*ian 10

    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);
Run Code Online (Sandbox Code Playgroud)