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 に答える