Create png UIImage from OpenGL drawing

I'm exporting my OpenGL drawings to a UIImage using the following method:

-(UIImage*)saveOpenGLDrawnToUIImage:(NSInteger)aWidth height:(NSInteger)aHeight {
    NSInteger myDataLength = aWidth * aHeight * 4;

    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, aWidth, aHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y < aHeight; y++)
        for(int x = 0; x < aWidth * 4; x++)
            buffer2[(aHeight-1 - y) * aWidth * 4 + x] = buffer[y * 4 * aWidth + x];

    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * aWidth;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

    CGImageRef imageRef = CGImageCreate(aWidth, aHeight, bitsPerComponent, bitsPerPixel, bytesPerRow,     colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

    UIImage *myImage = [UIImage imageWithCGImage:imageRef];
    return myImage;

But the background is always black instead of transparent.

I tried using CGImageRef imageRef = CGImageCreateWithPNGDataProvider(provider, NULL, NO, kCGRenderingIntentDefault); but it always generates nil.

How can I get this to process with a transparent background?


This is a question on how to create an image from raw RGBA data. I think you are missing a descriptor on the bitmap info to tell that you want an alpha channel...

Try Creating UIImage from raw RGBA data

The first comment is describing you should use kCGBitmapByteOrder32Big|kCGImageAlphaLast

Need Your Help

What's the best practice for Field Level security in MVC 3

I'm building a MVC 3 application that will be used by several different groups. In my views, I'm using all of the HTML Helpers to build out my UIs. (e.g. Html.DropDownListFor(), Html.EditorFor(),...

Self signed Certificate Based Authentication

java security certificate

I have started a project based on Client server communication in java. What i'm doing is client and server have their own self signed certificates. In initial communication both client and server w...