2016-11-08 45 views
0

我有一個程序,將加載一個JPEG圖像,並允許用戶在圖像上繪製並重新保存。保存RGB值爲JPEG使用libjpeg,得到奇怪的結果

我有裝載和繪圖工作,但是當我嘗試保存圖像我得到這樣的結果

Image

結果應該剛剛與線蝸牛的形象。

這是我的代碼

bool IOManager::save_jpg_to_file(const char *file_name) { 
struct jpeg_compress_struct cinfo; 

struct jpeg_error_mgr jerr; 

FILE * outfile; 
JSAMPROW row_pointer[1]; 
int row; 

JSAMPLE * image_buffer; 

cinfo.err = jpeg_std_error(&jerr); 
jpeg_create_compress(&cinfo); 

if ((outfile = fopen(file_name_.c_str(), "wb")) == NULL) { 
    fprintf(stderr, "can't open %s\n", file_name_); 
    return false; 
} 

jpeg_stdio_dest(&cinfo, outfile); 

int img_width = pixel_buffer_->width(); 
int img_height = pixel_buffer_->height(); 

cinfo.image_width = img_width; 
cinfo.image_height = img_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); 

unsigned char bytes[img_width * 3]; 

while (cinfo.next_scanline < cinfo.image_height) { 
    for (int i = 0; i < img_width; i+=3){ 
     ColorData colorData = pixel_buffer_->get_pixel(i, cinfo 
       .next_scanline); 
     bytes[i] = static_cast<int>(colorData.red()*255) & 0xff; 
     bytes[i+1] = static_cast<int>(colorData.green()*255) & 0xff; 
     bytes[i+2] = static_cast<int>(colorData.blue()*255) & 0xff; 
    } 
    row_pointer[0] = bytes; 
    (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); 
} 

jpeg_finish_compress(&cinfo); 
fclose(outfile); 
jpeg_destroy_compress(&cinfo); 

std::cout << "Done" << std::endl; 

return true; 
} 

PixelBuffer僅僅是一個RGB值的2D陣列。

我想不通它爲什麼會產生那些怪異的線,有什麼幫助?

+1

您確定需要跳過pixel_buffer中的每3個像素?你可能需要單獨計數,那裏增長較慢(即+ = 1) –

+0

真棒,似乎工作! –

+0

它看起來像是從灰度圖像開始並生成彩色圖像。你確定你的源代碼有3個組件嗎? – user3344003

回答

0

只是發表我的評論作爲一個單獨的答案。您似乎以錯誤的方式訪問像素緩衝區數據:在源緩衝區和目標緩衝區中,您跳過了3個像素,同時(給定您的代碼片段),看起來您需要處理每個像素的源代碼。確保迭代時只增加1而不是3增加索引pixel_buffer_