我试过遵循另一个答案,但似乎无法做到这一点。我有大约 8MiB 的 RBGX 位图可以使用 libjpeg-turbo 转换为内存中的 jpeg。如果我使用jpeg_stdio_dest
,我可以将整个内容写入文件,然后将文件读回,就可以了。然而,尝试使用jpeg_mem_dest
一直是个难题。我的设置与 相同jpeg_stdio_dest
,但 usingmem
似乎只分配了一次 4KiB,然后再也不分配任何空间。
我找不到有关如何使用的进一步说明的文档jpeg_mem_dest
,并且确实可以使用某些方向。
void compress(std::vector<unsigned char>& input) {
jpeg_compress_struct cinfo{};
jpeg_error_mgr err{};
cinfo.err = jpeg_std_error(&err);
jpeg_create_compress(&cinfo);
#if 0 // using this with an open FILE* out works
jpeg_stdio_dest(&cinfo, out);
#endif
cinfo.image_width = kWidth; // constants defined somewhere
cinfo.image_height = kHeight;
cinfo.input_components = 4;
cinfo.in_color_space = JCS_EXT_RGBX;
// what's wrong with this?
unsigned char* buf{};
unsigned long buf_sz{};
jpeg_mem_dest(&cinfo, &buf, &buf_sz);
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 70, true);
jpeg_start_compress(&cinfo, true);
while (cinfo.next_scanline < cinfo.image_height) {
auto row = static_cast<JSAMPROW>(&input[cinfo.next_scanline * 4 * kWidth]);
jpeg_write_scanlines(&cinfo, &row, 1);
// Always prints 4096, and buf never changes
std::cout << "buf_sz: " << buf_sz
<< " buf: " << static_cast<void*>(buf) << '\n';
}
jpeg_finish_compress(&cinfo);
// ...
// in reality, return the compressed data
}