2

I have a 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

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.

1
  • OK I think I solved it.. I found out that imageWithData is just creating images which have a format (png, jpeg) .. so I need to create a context first right? Commented Jul 12, 2011 at 6:55

1 Answer 1

11
    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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. Worked perfect. (Just had to change kCGImageAlphaPremultipliedLast to kCGImageAlphaPremultipliedFirst)
Please mark this answer as the correct one, since it worked ;)
If you need BGRA convertion, use kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Little instead for bitmap info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.