3

下面的代码帮助我使用 libjpg 将 OpenGL 输出转换为 JPEG 图像,但生成的图像是垂直翻转的......

代码完美运行,但最终图像被翻转我不知道为什么?!

unsigned char *pdata = new unsigned char[width*height*3];
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pdata);

    FILE *outfile;
    if ((outfile = fopen("sample.jpeg", "wb")) == NULL) {
        printf("can't open %s");
        exit(1);
      }

    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr       jerr;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_stdio_dest(&cinfo, outfile);

    cinfo.image_width      = width;
    cinfo.image_height     = height;
    cinfo.input_components = 3;
    cinfo.in_color_space   = JCS_RGB;

    jpeg_set_defaults(&cinfo);
    /*set the quality [0..100]  */
    jpeg_set_quality (&cinfo, 100, true);
    jpeg_start_compress(&cinfo, true);

    JSAMPROW row_pointer;
    int row_stride = width * 3;

    while (cinfo.next_scanline < cinfo.image_height) {
    row_pointer = (JSAMPROW) &pdata[cinfo.next_scanline*row_stride];
    jpeg_write_scanlines(&cinfo, &row_pointer, 1);
    }

    jpeg_finish_compress(&cinfo);

    fclose(outfile);

    jpeg_destroy_compress(&cinfo);
4

1 回答 1

5

OpenGL 的坐标系的原点位于图像的左下角。LIBJPEG 假设图像的原点在图像的左上角。进行以下更改以修复您的代码:

while (cinfo.next_scanline < cinfo.image_height)
{
    row_pointer = (JSAMPROW) &pdata[(cinfo.image_height-1-cinfo.next_scanline)*row_stride];
    jpeg_write_scanlines(&cinfo, &row_pointer, 1);
}
于 2012-02-23T20:07:00.013 回答