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?
    – Marco
    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);
3
  • 1
    Thank you very much. Worked perfect. (Just had to change kCGImageAlphaPremultipliedLast to kCGImageAlphaPremultipliedFirst)
    – Marco
    Jul 12, 2011 at 7:11
  • Please mark this answer as the correct one, since it worked ;) Jul 21, 2011 at 19:10
  • If you need BGRA convertion, use kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Little instead for bitmap info. Jun 20, 2018 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.