c++ - How to compress to memory with libjpeg-turbo using jpeg_mem_dest -
i've tried following another answer can't seem right. have 8mib of rbgx bitmap convert jpeg in memory using libjpeg-turbo. if use jpeg_stdio_dest can write whole thing file, read file in, , it's right. however, trying use jpeg_mem_dest has been puzzle. have same set jpeg_stdio_dest, using mem seems 1 allocation of 4kib , never allocate more space.
i can't find docs further instruction on how use jpeg_mem_dest, , use direction.
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 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 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); // prints 4096, , buf never changes std::cout << "buf_sz: " << buf_sz << " buf: " << static_cast<void*>(buf) << '\n'; } jpeg_finish_compress(&cinfo); // ... // in reality, return compressed data }
yeah, not intuitive @ all. programmer proposed jpeg_mem_dest() tweak did not have choice, extending existing api not easy when wasn't designed support feature in first place. unobvious variables don't updated until after jpeg_finish_compress() call. relevant code in library is:
methoddef(void) term_mem_destination (j_compress_ptr cinfo) { my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; *dest->outbuffer = dest->buffer; *dest->outsize = (unsigned long)(dest->bufsize - dest->pub.free_in_buffer); } note word "term". function called indirectly through function pointer:
global(void) jpeg_finish_compress (j_compress_ptr cinfo) { //... /* write eoi, final cleanup */ (*cinfo->marker->write_file_trailer) (cinfo); (*cinfo->dest->term_destination) (cinfo); //... } nothing can it. tweak std::cout code, move after loop accommodate way library works.
beware other gritty detail of function, not obvious. have free() buffer created. visible in provided cjpeg.c sample program, end of main().
Comments
Post a Comment