2014-10-01 140 views
1

我想使用libjpeg庫將圖像保存到內存(矢量)中。 我發現有funcitons:Libjpeg將圖像寫入內存數據

init_destination 
empty_output_buffer 
term_destination 

我的問題是如何做到這一點安全和正確的並行程序?我的功能可能會從不同的線程執行。 我想在C++和Visual Studio 2010中做到這一點。

其他具有回調函數的庫總是有額外的函數參數來存儲一些額外的數據。 我看不出任何添加任何附加參數的方法,例如指向我的本地矢量實例的指針。

編輯: MMY問題的很好的解決方案是在這裏:http://www.christian-etter.de/?cat=48

+0

可能重複[寫入內存緩衝區而不是使用libjpeg的文件?] (http://stackoverflow.com/questions/4559648/write-to-memory-buffer-instead-of-file-with-libjpeg) – 2014-10-01 14:48:59

+0

我發現這篇文章,但有一個全局向量,因此它不安全並行程序。 – AdamF 2014-10-01 14:50:32

+0

你看過其他答案嗎? – 2014-10-01 14:53:29

回答

2

的很好的解決方案在這裏描述:http://www.christian-etter.de/?cat=48

typedef struct _jpeg_destination_mem_mgr 
{ 
    jpeg_destination_mgr mgr; 
    std::vector<unsigned char> data; 
} jpeg_destination_mem_mgr; 

初始化:

static void mem_init_destination(j_compress_ptr cinfo) 
{ 
    jpeg_destination_mem_mgr* dst = (jpeg_destination_mem_mgr*)cinfo->dest; 
    dst->data.resize(JPEG_MEM_DST_MGR_BUFFER_SIZE); 
    cinfo->dest->next_output_byte = dst->data.data(); 
    cinfo->dest->free_in_buffer = dst->data.size(); 
} 

當我們完成那麼我們需要將緩衝區大小調整爲實際大小:

static void mem_term_destination(j_compress_ptr cinfo) 
{ 
    jpeg_destination_mem_mgr* dst = (jpeg_destination_mem_mgr*)cinfo->dest; 
    dst->data.resize(dst->data.size() - cinfo->dest->free_in_buffer); 
} 

當緩衝區大小太小,那麼我們需要增加它:

static boolean mem_empty_output_buffer(j_compress_ptr cinfo) 
{ 
    jpeg_destination_mem_mgr* dst = (jpeg_destination_mem_mgr*)cinfo->dest; 
    size_t oldsize = dst->data.size(); 
    dst->data.resize(oldsize + JPEG_MEM_DST_MGR_BUFFER_SIZE); 
    cinfo->dest->next_output_byte = dst->data.data() + oldsize; 
    cinfo->dest->free_in_buffer = JPEG_MEM_DST_MGR_BUFFER_SIZE; 
    return true; 
} 

回調配置:

static void jpeg_mem_dest(j_compress_ptr cinfo, jpeg_destination_mem_mgr * dst) 
{ 
    cinfo->dest = (jpeg_destination_mgr*)dst; 
    cinfo->dest->init_destination = mem_init_destination; 
    cinfo->dest->term_destination = mem_term_destination; 
    cinfo->dest->empty_output_buffer = mem_empty_output_buffer; 
} 

而且樣品用量:

jpeg_destination_mem_mgr dst_mem; 
jpeg_compress_struct_wrapper cinfo; 
j_compress_ptr pcinfo = cinfo; 
jpeg_mem_dest(cinfo, &dst_mem);