Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLPaint save image

I'm trying to develop a complex painting application on the iPhone. I'm currently drawing using Quartz (e.g. CGContext...). Unfortunately the Quartz overhead is just too slow for the type of drawing I'm doing, and I'm porting to OpenGL calls using the GLPaint example as a reference point.

Is there a way to get a UIImage/CGImage from the EAGLview class (the equivalent of Quartz's UIGraphicsGetImageFromCurrentImageContext)? Basically I need to save the pictures drawn by the GLPaint application.

like image 726
Drew Avatar asked Nov 29 '22 12:11

Drew


1 Answers

-(UIImage *) saveImageFromGLView
{
    NSInteger myDataLength = 320 * 480 * 4;
    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, 320, 480, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
    // gl renders "upside down" so swap top to bottom into new array.
    // there's gotta be a better way, but this works.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y <480; y++)
    {
        for(int x = 0; x <320 * 4; x++)
        {
            buffer2[(479 - y) * 320 * 4 + x] = buffer[y * 4 * 320 + x];
        }
    }
    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
    // prep the ingredients
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * 320;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    // make the cgimage
    CGImageRef imageRef = CGImageCreate(320, 480, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
    // then make the uiimage from that
    UIImage *myImage = [UIImage imageWithCGImage:imageRef];
    return myImage;
}
like image 190
Rajavanya Subramaniyan Avatar answered Dec 16 '22 01:12

Rajavanya Subramaniyan