3

我正在寻找方法来获取我的 opengl(作为 UIImage)的内容,然后将其保存到文件中。我现在正在尝试 glReadPixels,尽管我不确定我是否在做正确的事情,我应该做什么样的 malloc。我收集到在 OSX 上它是 GL_BGRA 但在 iPhone 上不起作用......

4

3 回答 3

2

所有 OpenGL|ES 兼容的 GL 实现都必须支持 GL_RGBA 作为 glReadPixels 的参数。

如果您的 OpenGL|Es 支持

GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 

扩展名您还可以查询本机格式。glReadPixels 会将此格式理解为 glReadPixels 的参数,并允许您直接获取本机格式的像素数据。这通常比 GL_RGBA 快一点。

查看头文件或通过 glGetString 查询扩展支持。

于 2008-11-24T14:46:58.610 回答
1

查找“技术问答 QA1704 OpenGL ES View Snapshot”,其中 Apple 给出了一个可行的示例,包括 Nils 的“更好的方法”来取消翻转图像。它会带你到你的 UIImage,然后从那里跟随 Nils 获取另存为文件的方法。

于 2011-04-15T15:01:53.520 回答
1

从 OpenGL ES 视图中获取数据:

-(UIImage *) snapshot {
    NSInteger myDataLength = backingWidth * backingHeight * 4;
    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, backingWidth, backingHeight, 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 <backingHeight; y++)
    {
        for(int x = 0; x <backingWidth * 4; x++)
        {
            buffer2[((backingHeight - 1) - y) * backingWidth * 4 + x] = buffer[y * 4 * backingWidth + x];
        }
    }
    free(buffer);
    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);
    // prep the ingredients
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * backingWidth;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    // make the cgimage
    CGImageRef imageRef = CGImageCreate(backingWidth, backingHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
    // then make the uiimage from that
    UIImage *myImage = [UIImage imageWithCGImage:imageRef];
    return myImage;
}

然后保存图像:

-(void) saveImage:(UIImage *)image {}
    // Create paths to output images
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];

    // Write a UIImage to JPEG with minimum compression (best quality)
    // The value 'image' must be a UIImage object
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];

    // Write image to PNG
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
}
于 2010-07-26T09:39:00.967 回答