Allen
Allen

Reputation: 6882

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?

Upvotes: 3

Views: 254

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16774

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

Upvotes: 2

Related Questions