2 * libjpeg8-mem-dest - an example about reusing the memory buffer with libjpeg8
4 * Copyright (C) 2013 Antonio Ospite <ospite@studenti.unina.it>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 static unsigned char *new_image(void)
33 image = malloc(WIDTH * HEIGHT * 3 * sizeof(*image));
39 for (i = 0; i < WIDTH * HEIGHT * 3; i++)
40 image[i] = rand() % 0xff;
48 struct jpeg_compress_struct cinfo;
49 struct jpeg_error_mgr jerr;
50 JSAMPROW row_pointer[1];
53 unsigned char *out_buf;
54 unsigned long out_buf_size;
56 unsigned char *input_image;
58 cinfo.err = jpeg_std_error(&jerr);
59 jpeg_create_compress(&cinfo);
63 jpeg_mem_dest(&cinfo, &out_buf, &out_buf_size);
65 cinfo.image_width = WIDTH;
66 cinfo.image_height = HEIGHT;
67 cinfo.input_components = 3;
68 cinfo.in_color_space = JCS_RGB;
70 jpeg_set_defaults(&cinfo);
71 jpeg_set_quality(&cinfo, 80, TRUE);
73 row_stride = WIDTH * 3;
79 input_image = new_image();
81 jpeg_start_compress(&cinfo, TRUE);
82 while(cinfo.next_scanline < cinfo.image_height) {
83 row_pointer[0] = &input_image[cinfo.next_scanline * row_stride];
84 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
86 jpeg_finish_compress(&cinfo);
90 /* Is out_buf_size the number of bytes of the jpeg image, or the
91 * size of the allocated buffer? */
92 fprintf(stderr, "out_buf: %p out_buf_size: %ld\n", out_buf, out_buf_size);
94 char filename[256] = { 0 };
97 snprintf(filename, sizeof(filename), "out%03d.jpg", i);
98 out_file = fopen(filename, "wb");
99 fwrite(out_buf, out_buf_size, 1, out_file);
105 * Rewind the buffer, taken from:
106 * http://sourceforge.net/p/libjpeg-turbo/discussion/1086868/thread/b797ffaf/
108 cinfo.dest->free_in_buffer += cinfo.dest->next_output_byte - out_buf;
109 cinfo.dest->next_output_byte = out_buf;
111 /* The code above avoids freeing and allocating a NEW buffer
112 * Isn't there a more straightforward way to recycle the old
113 * buffer after we consumed its content?
118 jpeg_mem_dest(&cinfo, &out_buf, &out_buf_size);
122 jpeg_destroy_compress(&cinfo);