2012-05-07 417 views
2

我需要一種簡單的方法將包含RGB數據的緩衝區轉換爲jpeg。我已經嘗試過使用libjpeg,但我根本無法讓它正常工作。例如,在保存緩衝區作爲位圖產生這樣的:RGB緩衝區到JPEG緩衝區,這裏有什麼問題?

Bitmap Screenshot

使用的libjpeg編碼在存儲器中的相同圖像產生這樣的:

enter image description here

並直接保存圖像到文件只是中止沒有發出警告,錯誤或任何事情。

我當然需要一些可行的東西!

這是我在做什麼

void OnKeyPress(unsigned char key, int x, int y) { 
    if (key != static_cast<unsigned char>('p')) 
    return; 

    int width = g_current_width; 
    int height = g_current_height; 
    boost::scoped_array<boost::uint8_t> buffer(new boost::uint8_t[3 * width * height]); 

    glReadBuffer(GL_FRONT); 
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, 
       reinterpret_cast<GLvoid *>(buffer.get())); 
    glReadBuffer(GL_BACK); 

    FlipImage(buffer.get(), width, height); 

    // Generate a BMP files for testing purposes 
    SaveRGB("screenshot.bmp", buffer.get(), width, height); 

    jpeg_compress_struct cinfo; 
    jpeg_error_mgr jerr; 
    cinfo.err = jpeg_std_error(&jerr); 
    jerr.trace_level = 10; 
    jpeg_create_compress(&cinfo); 
    boost::uint8_t *jpeg_buffer_raw = NULL; 
    unsigned long outbuffer_size = 0; 
    jpeg_mem_dest(&cinfo, &jpeg_buffer_raw, &outbuffer_size); 

    cinfo.image_width = width; 
    cinfo.image_height = height; 
    cinfo.input_components = 3; 
    cinfo.in_color_space = JCS_RGB; 
    jpeg_set_defaults(&cinfo); 

    jpeg_set_quality(&cinfo, 100, true); 
    jpeg_start_compress(&cinfo, true); 
    int row_stride = width * 3; 
    JSAMPROW row_pointer[1]; 
    int counter = 0; 
    std::cout << boost::format("height: %d\n") % height; 
    boost::uint8_t *r_buffer = buffer.get(); 
    while (cinfo.next_scanline < cinfo.image_height) { 
    row_pointer[0] = &r_buffer[cinfo.next_scanline * row_stride]; 
    jpeg_write_scanlines(&cinfo, row_pointer, 1); 
    std::cout << boost::format("current line: %d\n") % (counter++); 
    } 
    jpeg_finish_compress(&cinfo); 
    jpeg_destroy_compress(&cinfo); 
    std::ofstream jpegfile("screenshot.jpg"); 
    jpegfile.write(reinterpret_cast<const char*>(jpeg_buffer_raw), outbuffer_size); 
    jpegfile.flush(); 
    // calling free(jpeg_buffer_raw); or delete[] jpeg_buffer_raw; generates an error 
} 
+3

怎麼樣你叫libjpeg?向我們展示代碼。 – Thomas

+1

SO是一個問答網站。你的問題是什麼? –

+0

SO夥計們,我用我使用的代碼更新了這個問題。 – Sambatyon

回答

2

所以,我發現這個問題,這是在最後,輸出文件應該已經初始化是這樣的:

std::ofstream jpegfile("screenshot.jpg", std::ios_base::out | std::ios_base::binary);