added support for reading resolution information from TIFF, JPEG and BMP formats...
[wxWidgets.git] / src / common / imagjpeg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagjpeg.cpp
3 // Purpose: wxImage JPEG handler
4 // Author: Vaclav Slavik
5 // RCS-ID: $Id$
6 // Copyright: (c) Vaclav Slavik
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #ifdef __BORLANDC__
14 #pragma hdrstop
15 #endif
16
17 #if wxUSE_IMAGE && wxUSE_LIBJPEG
18
19 #include "wx/imagjpeg.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/app.h"
24 #include "wx/intl.h"
25 #include "wx/bitmap.h"
26 #include "wx/module.h"
27 #endif
28
29 // A hack based on one from tif_jpeg.c to overcome the problem on Windows
30 // of rpcndr.h defining boolean with a different type to the jpeg headers.
31 //
32 // This hack is only necessary for an external jpeg library, the builtin one
33 // usually used on Windows doesn't use the type boolean, so always works.
34 //
35 #ifdef wxHACK_BOOLEAN
36 #define HAVE_BOOLEAN
37 #define boolean wxHACK_BOOLEAN
38 #endif
39
40 extern "C"
41 {
42 #if defined(__WXMSW__)
43 #define XMD_H
44 #endif
45 #include "jpeglib.h"
46 }
47
48 #ifndef HAVE_WXJPEG_BOOLEAN
49 typedef boolean wxjpeg_boolean;
50 #endif
51
52 #include "wx/filefn.h"
53 #include "wx/wfstream.h"
54
55 // For memcpy
56 #include <string.h>
57 // For JPEG library error handling
58 #include <setjmp.h>
59
60 #ifdef __SALFORDC__
61 #undef FAR
62 #endif
63
64 // ----------------------------------------------------------------------------
65 // types
66 // ----------------------------------------------------------------------------
67
68 // the standard definition of METHODDEF(type) from jmorecfg.h is "static type"
69 // which means that we can't declare the method functions as extern "C" - the
70 // compiler (rightfully) complains about the multiple storage classes in
71 // declaration
72 //
73 // so we only add extern "C" when using our own, modified, jmorecfg.h - and use
74 // whatever we have in the system headers if this is what we use hoping that it
75 // should be ok (can't do anything else)
76 #ifdef JPEG_METHOD_LINKAGE
77 #define CPP_METHODDEF(type) extern "C" METHODDEF(type)
78 #else // not using our jmorecfg.h header
79 #define CPP_METHODDEF(type) METHODDEF(type)
80 #endif
81
82 //-----------------------------------------------------------------------------
83 // wxJPEGHandler
84 //-----------------------------------------------------------------------------
85
86 IMPLEMENT_DYNAMIC_CLASS(wxJPEGHandler,wxImageHandler)
87
88 #if wxUSE_STREAMS
89
90 //------------- JPEG Data Source Manager
91
92 #define JPEG_IO_BUFFER_SIZE 2048
93
94 typedef struct {
95 struct jpeg_source_mgr pub; /* public fields */
96
97 JOCTET* buffer; /* start of buffer */
98 wxInputStream *stream;
99 } wx_source_mgr;
100
101 typedef wx_source_mgr * wx_src_ptr;
102
103 extern "C"
104 {
105
106 CPP_METHODDEF(void) wx_init_source ( j_decompress_ptr WXUNUSED(cinfo) )
107 {
108 }
109
110 CPP_METHODDEF(wxjpeg_boolean) wx_fill_input_buffer ( j_decompress_ptr cinfo )
111 {
112 wx_src_ptr src = (wx_src_ptr) cinfo->src;
113
114 src->pub.next_input_byte = src->buffer;
115 src->pub.bytes_in_buffer = src->stream->Read(src->buffer, JPEG_IO_BUFFER_SIZE).LastRead();
116
117 if (src->pub.bytes_in_buffer == 0) // check for end-of-stream
118 {
119 // Insert a fake EOI marker
120 src->buffer[0] = 0xFF;
121 src->buffer[1] = JPEG_EOI;
122 src->pub.bytes_in_buffer = 2;
123 }
124 return TRUE;
125 }
126
127 CPP_METHODDEF(void) wx_skip_input_data ( j_decompress_ptr cinfo, long num_bytes )
128 {
129 if (num_bytes > 0)
130 {
131 wx_src_ptr src = (wx_src_ptr) cinfo->src;
132
133 while (num_bytes > (long)src->pub.bytes_in_buffer)
134 {
135 num_bytes -= (long) src->pub.bytes_in_buffer;
136 src->pub.fill_input_buffer(cinfo);
137 }
138 src->pub.next_input_byte += (size_t) num_bytes;
139 src->pub.bytes_in_buffer -= (size_t) num_bytes;
140 }
141 }
142
143 CPP_METHODDEF(void) wx_term_source ( j_decompress_ptr cinfo )
144 {
145 wx_src_ptr src = (wx_src_ptr) cinfo->src;
146
147 if (src->pub.bytes_in_buffer > 0)
148 src->stream->SeekI(-(long)src->pub.bytes_in_buffer, wxFromCurrent);
149 delete[] src->buffer;
150 }
151
152
153 // JPEG error manager:
154
155 struct wx_error_mgr {
156 struct jpeg_error_mgr pub; /* "public" fields */
157
158 jmp_buf setjmp_buffer; /* for return to caller */
159 };
160
161 typedef struct wx_error_mgr * wx_error_ptr;
162
163 /*
164 * Here's the routine that will replace the standard error_exit method:
165 */
166
167 CPP_METHODDEF(void) wx_error_exit (j_common_ptr cinfo)
168 {
169 /* cinfo->err really points to a wx_error_mgr struct, so coerce pointer */
170 wx_error_ptr myerr = (wx_error_ptr) cinfo->err;
171
172 /* Always display the message. */
173 /* We could postpone this until after returning, if we chose. */
174 (*cinfo->err->output_message) (cinfo);
175
176 /* Return control to the setjmp point */
177 longjmp(myerr->setjmp_buffer, 1);
178 }
179
180 /*
181 * This will replace the standard output_message method when the user
182 * wants us to be silent (verbose==false). We must have such method instead of
183 * simply using NULL for cinfo->err->output_message because it's called
184 * unconditionally from within libjpeg when there's "garbage input".
185 */
186 CPP_METHODDEF(void) wx_ignore_message (j_common_ptr WXUNUSED(cinfo))
187 {
188 }
189
190 void wx_jpeg_io_src( j_decompress_ptr cinfo, wxInputStream& infile )
191 {
192 wx_src_ptr src;
193
194 if (cinfo->src == NULL) { /* first time for this JPEG object? */
195 cinfo->src = (struct jpeg_source_mgr *)
196 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
197 sizeof(wx_source_mgr));
198 }
199 src = (wx_src_ptr) cinfo->src;
200 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
201 src->buffer = new JOCTET[JPEG_IO_BUFFER_SIZE];
202 src->pub.next_input_byte = NULL; /* until buffer loaded */
203 src->stream = &infile;
204
205 src->pub.init_source = wx_init_source;
206 src->pub.fill_input_buffer = wx_fill_input_buffer;
207 src->pub.skip_input_data = wx_skip_input_data;
208 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
209 src->pub.term_source = wx_term_source;
210 }
211
212 } // extern "C"
213
214 static inline void wx_cmyk_to_rgb(unsigned char* rgb, const unsigned char* cmyk)
215 {
216 register int k = 255 - cmyk[3];
217 register int k2 = cmyk[3];
218 register int c;
219
220 c = k + k2 * (255 - cmyk[0]) / 255;
221 rgb[0] = (unsigned char)((c > 255) ? 0 : (255 - c));
222
223 c = k + k2 * (255 - cmyk[1]) / 255;
224 rgb[1] = (unsigned char)((c > 255) ? 0 : (255 - c));
225
226 c = k + k2 * (255 - cmyk[2]) / 255;
227 rgb[2] = (unsigned char)((c > 255) ? 0 : (255 - c));
228 }
229
230 // temporarily disable the warning C4611 (interaction between '_setjmp' and
231 // C++ object destruction is non-portable) - I don't see any dtors here
232 #ifdef __VISUALC__
233 #pragma warning(disable:4611)
234 #endif /* VC++ */
235
236 bool wxJPEGHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int WXUNUSED(index) )
237 {
238 struct jpeg_decompress_struct cinfo;
239 struct wx_error_mgr jerr;
240 unsigned char *ptr;
241
242 image->Destroy();
243 cinfo.err = jpeg_std_error( &jerr.pub );
244 jerr.pub.error_exit = wx_error_exit;
245
246 if (!verbose)
247 cinfo.err->output_message = wx_ignore_message;
248
249 /* Establish the setjmp return context for wx_error_exit to use. */
250 if (setjmp(jerr.setjmp_buffer)) {
251 /* If we get here, the JPEG code has signaled an error.
252 * We need to clean up the JPEG object, close the input file, and return.
253 */
254 if (verbose)
255 wxLogError(_("JPEG: Couldn't load - file is probably corrupted."));
256 (cinfo.src->term_source)(&cinfo);
257 jpeg_destroy_decompress(&cinfo);
258 if (image->Ok()) image->Destroy();
259 return false;
260 }
261
262 jpeg_create_decompress( &cinfo );
263 wx_jpeg_io_src( &cinfo, stream );
264 jpeg_read_header( &cinfo, TRUE );
265
266 int bytesPerPixel;
267 if ((cinfo.out_color_space == JCS_CMYK) || (cinfo.out_color_space == JCS_YCCK))
268 {
269 cinfo.out_color_space = JCS_CMYK;
270 bytesPerPixel = 4;
271 }
272 else // all the rest is treated as RGB
273 {
274 cinfo.out_color_space = JCS_RGB;
275 bytesPerPixel = 3;
276 }
277
278 jpeg_start_decompress( &cinfo );
279
280 image->Create( cinfo.image_width, cinfo.image_height );
281 if (!image->Ok()) {
282 jpeg_finish_decompress( &cinfo );
283 jpeg_destroy_decompress( &cinfo );
284 return false;
285 }
286 image->SetMask( false );
287 ptr = image->GetData();
288
289 unsigned stride = cinfo.output_width * bytesPerPixel;
290 JSAMPARRAY tempbuf = (*cinfo.mem->alloc_sarray)
291 ((j_common_ptr) &cinfo, JPOOL_IMAGE, stride, 1 );
292
293 while ( cinfo.output_scanline < cinfo.output_height )
294 {
295 jpeg_read_scanlines( &cinfo, tempbuf, 1 );
296 if (cinfo.out_color_space == JCS_RGB)
297 {
298 memcpy( ptr, tempbuf[0], stride );
299 ptr += stride;
300 }
301 else // CMYK
302 {
303 const unsigned char* inptr = (const unsigned char*) tempbuf[0];
304 for (size_t i = 0; i < cinfo.output_width; i++)
305 {
306 wx_cmyk_to_rgb(ptr, inptr);
307 ptr += 3;
308 inptr += 4;
309 }
310 }
311 }
312
313 // set up resolution if available: it's part of optional JFIF APP0 chunk
314 if ( cinfo.saw_JFIF_marker )
315 {
316 image->SetOption(wxIMAGE_OPTION_RESOLUTIONX, cinfo.X_density);
317 image->SetOption(wxIMAGE_OPTION_RESOLUTIONY, cinfo.Y_density);
318
319 // we use the same values for this option as libjpeg so we don't need
320 // any conversion here
321 image->SetOption(wxIMAGE_OPTION_RESOLUTIONUNIT, cinfo.density_unit);
322 }
323
324 jpeg_finish_decompress( &cinfo );
325 jpeg_destroy_decompress( &cinfo );
326 return true;
327 }
328
329 typedef struct {
330 struct jpeg_destination_mgr pub;
331
332 wxOutputStream *stream;
333 JOCTET * buffer;
334 } wx_destination_mgr;
335
336 typedef wx_destination_mgr * wx_dest_ptr;
337
338 #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
339
340 extern "C"
341 {
342
343 CPP_METHODDEF(void) wx_init_destination (j_compress_ptr cinfo)
344 {
345 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
346
347 /* Allocate the output buffer --- it will be released when done with image */
348 dest->buffer = (JOCTET *)
349 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
350 OUTPUT_BUF_SIZE * sizeof(JOCTET));
351 dest->pub.next_output_byte = dest->buffer;
352 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
353 }
354
355 CPP_METHODDEF(wxjpeg_boolean) wx_empty_output_buffer (j_compress_ptr cinfo)
356 {
357 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
358
359 dest->stream->Write(dest->buffer, OUTPUT_BUF_SIZE);
360 dest->pub.next_output_byte = dest->buffer;
361 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
362 return TRUE;
363 }
364
365 CPP_METHODDEF(void) wx_term_destination (j_compress_ptr cinfo)
366 {
367 wx_dest_ptr dest = (wx_dest_ptr) cinfo->dest;
368 size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
369 /* Write any data remaining in the buffer */
370 if (datacount > 0)
371 dest->stream->Write(dest->buffer, datacount);
372 }
373
374 GLOBAL(void) wx_jpeg_io_dest (j_compress_ptr cinfo, wxOutputStream& outfile)
375 {
376 wx_dest_ptr dest;
377
378 if (cinfo->dest == NULL) { /* first time for this JPEG object? */
379 cinfo->dest = (struct jpeg_destination_mgr *)
380 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
381 sizeof(wx_destination_mgr));
382 }
383
384 dest = (wx_dest_ptr) cinfo->dest;
385 dest->pub.init_destination = wx_init_destination;
386 dest->pub.empty_output_buffer = wx_empty_output_buffer;
387 dest->pub.term_destination = wx_term_destination;
388 dest->stream = &outfile;
389 }
390
391 } // extern "C"
392
393 bool wxJPEGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
394 {
395 struct jpeg_compress_struct cinfo;
396 struct wx_error_mgr jerr;
397 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
398 JSAMPLE *image_buffer;
399 int stride; /* physical row width in image buffer */
400
401 cinfo.err = jpeg_std_error(&jerr.pub);
402 jerr.pub.error_exit = wx_error_exit;
403
404 if (!verbose)
405 cinfo.err->output_message = wx_ignore_message;
406
407 /* Establish the setjmp return context for wx_error_exit to use. */
408 if (setjmp(jerr.setjmp_buffer))
409 {
410 /* If we get here, the JPEG code has signaled an error.
411 * We need to clean up the JPEG object, close the input file, and return.
412 */
413 if (verbose)
414 wxLogError(_("JPEG: Couldn't save image."));
415 jpeg_destroy_compress(&cinfo);
416 return false;
417 }
418
419 jpeg_create_compress(&cinfo);
420 wx_jpeg_io_dest(&cinfo, stream);
421
422 cinfo.image_width = image->GetWidth();
423 cinfo.image_height = image->GetHeight();
424 cinfo.input_components = 3;
425 cinfo.in_color_space = JCS_RGB;
426 jpeg_set_defaults(&cinfo);
427
428 // TODO: 3rd parameter is force_baseline, what value should this be?
429 // Code says: "If force_baseline is TRUE, the computed quantization table entries
430 // are limited to 1..255 for JPEG baseline compatibility."
431 // 'Quality' is a number between 0 (terrible) and 100 (very good).
432 // The default (in jcparam.c, jpeg_set_defaults) is 75,
433 // and force_baseline is TRUE.
434 if (image->HasOption(wxIMAGE_OPTION_QUALITY))
435 jpeg_set_quality(&cinfo, image->GetOptionInt(wxIMAGE_OPTION_QUALITY), TRUE);
436
437 // set the resolution fields in the output file
438 int resX, resY;
439 wxImageResolution res = GetResolutionFromOptions(*image, &resX, &resY);
440 if ( res != wxIMAGE_RESOLUTION_NONE )
441 {
442 cinfo.X_density = resX;
443 cinfo.Y_density = resY;
444
445 // it so happens that wxIMAGE_RESOLUTION_INCHES/CM values are the same
446 // ones as used by libjpeg, so we can assign them directly
447 cinfo.density_unit = res;
448 }
449
450 jpeg_start_compress(&cinfo, TRUE);
451
452 stride = cinfo.image_width * 3; /* JSAMPLEs per row in image_buffer */
453 image_buffer = image->GetData();
454 while (cinfo.next_scanline < cinfo.image_height) {
455 row_pointer[0] = &image_buffer[cinfo.next_scanline * stride];
456 jpeg_write_scanlines( &cinfo, row_pointer, 1 );
457 }
458 jpeg_finish_compress(&cinfo);
459 jpeg_destroy_compress(&cinfo);
460
461 return true;
462 }
463
464 #ifdef __VISUALC__
465 #pragma warning(default:4611)
466 #endif /* VC++ */
467
468 bool wxJPEGHandler::DoCanRead( wxInputStream& stream )
469 {
470 unsigned char hdr[2];
471
472 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
473 return false;
474
475 return hdr[0] == 0xFF && hdr[1] == 0xD8;
476 }
477
478 #endif // wxUSE_STREAMS
479
480 #endif // wxUSE_LIBJPEG