1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagjpeg.cpp
3 // Purpose: wxImage JPEG handler
4 // Author: Vaclav Slavik
5 // Copyright: (c) Vaclav Slavik
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
9 // For compilers that support precompilation, includes "wx.h".
10 #include "wx/wxprec.h"
16 #if wxUSE_IMAGE && wxUSE_LIBJPEG
18 #include "wx/imagjpeg.h"
19 #include "wx/versioninfo.h"
25 #include "wx/bitmap.h"
26 #include "wx/module.h"
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.
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.
37 #define boolean wxHACK_BOOLEAN
42 #if defined(__WXMSW__)
48 #ifndef HAVE_WXJPEG_BOOLEAN
49 typedef boolean wxjpeg_boolean
;
52 #include "wx/filefn.h"
53 #include "wx/wfstream.h"
57 // For JPEG library error handling
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
64 // the standard definition of METHODDEF(type) from jmorecfg.h is "static type"
65 // which means that we can't declare the method functions as extern "C" - the
66 // compiler (rightfully) complains about the multiple storage classes in
69 // so we only add extern "C" when using our own, modified, jmorecfg.h - and use
70 // whatever we have in the system headers if this is what we use hoping that it
71 // should be ok (can't do anything else)
72 #ifdef JPEG_METHOD_LINKAGE
73 #define CPP_METHODDEF(type) extern "C" METHODDEF(type)
74 #else // not using our jmorecfg.h header
75 #define CPP_METHODDEF(type) METHODDEF(type)
78 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
82 IMPLEMENT_DYNAMIC_CLASS(wxJPEGHandler
,wxImageHandler
)
86 //------------- JPEG Data Source Manager
88 #define JPEG_IO_BUFFER_SIZE 2048
91 struct jpeg_source_mgr pub
; /* public fields */
93 JOCTET
* buffer
; /* start of buffer */
94 wxInputStream
*stream
;
97 typedef wx_source_mgr
* wx_src_ptr
;
102 CPP_METHODDEF(void) wx_init_source ( j_decompress_ptr
WXUNUSED(cinfo
) )
106 CPP_METHODDEF(wxjpeg_boolean
) wx_fill_input_buffer ( j_decompress_ptr cinfo
)
108 wx_src_ptr src
= (wx_src_ptr
) cinfo
->src
;
110 src
->pub
.next_input_byte
= src
->buffer
;
111 src
->pub
.bytes_in_buffer
= src
->stream
->Read(src
->buffer
, JPEG_IO_BUFFER_SIZE
).LastRead();
113 if (src
->pub
.bytes_in_buffer
== 0) // check for end-of-stream
115 // Insert a fake EOI marker
116 src
->buffer
[0] = 0xFF;
117 src
->buffer
[1] = JPEG_EOI
;
118 src
->pub
.bytes_in_buffer
= 2;
123 CPP_METHODDEF(void) wx_skip_input_data ( j_decompress_ptr cinfo
, long num_bytes
)
127 wx_src_ptr src
= (wx_src_ptr
) cinfo
->src
;
129 while (num_bytes
> (long)src
->pub
.bytes_in_buffer
)
131 num_bytes
-= (long) src
->pub
.bytes_in_buffer
;
132 src
->pub
.fill_input_buffer(cinfo
);
134 src
->pub
.next_input_byte
+= (size_t) num_bytes
;
135 src
->pub
.bytes_in_buffer
-= (size_t) num_bytes
;
139 CPP_METHODDEF(void) wx_term_source ( j_decompress_ptr cinfo
)
141 wx_src_ptr src
= (wx_src_ptr
) cinfo
->src
;
143 if (src
->pub
.bytes_in_buffer
> 0)
144 src
->stream
->SeekI(-(long)src
->pub
.bytes_in_buffer
, wxFromCurrent
);
145 delete[] src
->buffer
;
149 // JPEG error manager:
151 struct wx_error_mgr
: public jpeg_error_mgr
153 jmp_buf setjmp_buffer
; /* for return to caller */
157 * Here's the routine that will replace the standard error_exit method:
160 CPP_METHODDEF(void) wx_error_exit (j_common_ptr cinfo
)
162 /* cinfo->err really points to a wx_error_mgr struct, so coerce pointer */
163 wx_error_mgr
* const jerr
= (wx_error_mgr
*) cinfo
->err
;
165 /* Always display the message. */
166 /* We could postpone this until after returning, if we chose. */
167 (*cinfo
->err
->output_message
) (cinfo
);
169 /* Return control to the setjmp point */
170 longjmp(jerr
->setjmp_buffer
, 1);
174 * This will replace the standard output_message method when the user
175 * wants us to be silent (verbose==false). We must have such method instead of
176 * simply using NULL for cinfo->err->output_message because it's called
177 * unconditionally from within libjpeg when there's "garbage input".
179 CPP_METHODDEF(void) wx_ignore_message (j_common_ptr
WXUNUSED(cinfo
))
183 void wx_jpeg_io_src( j_decompress_ptr cinfo
, wxInputStream
& infile
)
187 if (cinfo
->src
== NULL
) { /* first time for this JPEG object? */
188 cinfo
->src
= (struct jpeg_source_mgr
*)
189 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_PERMANENT
,
190 sizeof(wx_source_mgr
));
192 src
= (wx_src_ptr
) cinfo
->src
;
193 src
->pub
.bytes_in_buffer
= 0; /* forces fill_input_buffer on first read */
194 src
->buffer
= new JOCTET
[JPEG_IO_BUFFER_SIZE
];
195 src
->pub
.next_input_byte
= NULL
; /* until buffer loaded */
196 src
->stream
= &infile
;
198 src
->pub
.init_source
= wx_init_source
;
199 src
->pub
.fill_input_buffer
= wx_fill_input_buffer
;
200 src
->pub
.skip_input_data
= wx_skip_input_data
;
201 src
->pub
.resync_to_restart
= jpeg_resync_to_restart
; /* use default method */
202 src
->pub
.term_source
= wx_term_source
;
207 static inline void wx_cmyk_to_rgb(unsigned char* rgb
, const unsigned char* cmyk
)
209 register int k
= 255 - cmyk
[3];
210 register int k2
= cmyk
[3];
213 c
= k
+ k2
* (255 - cmyk
[0]) / 255;
214 rgb
[0] = (unsigned char)((c
> 255) ? 0 : (255 - c
));
216 c
= k
+ k2
* (255 - cmyk
[1]) / 255;
217 rgb
[1] = (unsigned char)((c
> 255) ? 0 : (255 - c
));
219 c
= k
+ k2
* (255 - cmyk
[2]) / 255;
220 rgb
[2] = (unsigned char)((c
> 255) ? 0 : (255 - c
));
223 // temporarily disable the warning C4611 (interaction between '_setjmp' and
224 // C++ object destruction is non-portable) - I don't see any dtors here
226 #pragma warning(disable:4611)
229 bool wxJPEGHandler::LoadFile( wxImage
*image
, wxInputStream
& stream
, bool verbose
, int WXUNUSED(index
) )
231 wxCHECK_MSG( image
, false, "NULL image pointer" );
233 struct jpeg_decompress_struct cinfo
;
237 // save this before calling Destroy()
238 const unsigned maxWidth
= image
->GetOptionInt(wxIMAGE_OPTION_MAX_WIDTH
),
239 maxHeight
= image
->GetOptionInt(wxIMAGE_OPTION_MAX_HEIGHT
);
242 cinfo
.err
= jpeg_std_error( &jerr
);
243 jerr
.error_exit
= wx_error_exit
;
246 cinfo
.err
->output_message
= wx_ignore_message
;
248 /* Establish the setjmp return context for wx_error_exit to use. */
249 if (setjmp(jerr
.setjmp_buffer
)) {
250 /* If we get here, the JPEG code has signaled an error.
251 * We need to clean up the JPEG object, close the input file, and return.
255 wxLogError(_("JPEG: Couldn't load - file is probably corrupted."));
257 (cinfo
.src
->term_source
)(&cinfo
);
258 jpeg_destroy_decompress(&cinfo
);
259 if (image
->IsOk()) image
->Destroy();
263 jpeg_create_decompress( &cinfo
);
264 wx_jpeg_io_src( &cinfo
, stream
);
265 jpeg_read_header( &cinfo
, TRUE
);
268 if ((cinfo
.out_color_space
== JCS_CMYK
) || (cinfo
.out_color_space
== JCS_YCCK
))
270 cinfo
.out_color_space
= JCS_CMYK
;
273 else // all the rest is treated as RGB
275 cinfo
.out_color_space
= JCS_RGB
;
279 // scale the picture to fit in the specified max size if necessary
280 if ( maxWidth
> 0 || maxHeight
> 0 )
282 unsigned& scale
= cinfo
.scale_denom
;
283 while ( (maxWidth
&& (cinfo
.image_width
/ scale
> maxWidth
)) ||
284 (maxHeight
&& (cinfo
.image_height
/ scale
> maxHeight
)) )
290 jpeg_start_decompress( &cinfo
);
292 image
->Create( cinfo
.output_width
, cinfo
.output_height
);
293 if (!image
->IsOk()) {
294 jpeg_finish_decompress( &cinfo
);
295 jpeg_destroy_decompress( &cinfo
);
298 image
->SetMask( false );
299 ptr
= image
->GetData();
301 unsigned stride
= cinfo
.output_width
* bytesPerPixel
;
302 JSAMPARRAY tempbuf
= (*cinfo
.mem
->alloc_sarray
)
303 ((j_common_ptr
) &cinfo
, JPOOL_IMAGE
, stride
, 1 );
305 while ( cinfo
.output_scanline
< cinfo
.output_height
)
307 jpeg_read_scanlines( &cinfo
, tempbuf
, 1 );
308 if (cinfo
.out_color_space
== JCS_RGB
)
310 memcpy( ptr
, tempbuf
[0], stride
);
315 const unsigned char* inptr
= (const unsigned char*) tempbuf
[0];
316 for (size_t i
= 0; i
< cinfo
.output_width
; i
++)
318 wx_cmyk_to_rgb(ptr
, inptr
);
325 // set up resolution if available: it's part of optional JFIF APP0 chunk
326 if ( cinfo
.saw_JFIF_marker
)
328 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONX
, cinfo
.X_density
);
329 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONY
, cinfo
.Y_density
);
331 // we use the same values for this option as libjpeg so we don't need
332 // any conversion here
333 image
->SetOption(wxIMAGE_OPTION_RESOLUTIONUNIT
, cinfo
.density_unit
);
336 if ( cinfo
.image_width
!= cinfo
.output_width
|| cinfo
.image_height
!= cinfo
.output_height
)
338 // save the original image size
339 image
->SetOption(wxIMAGE_OPTION_ORIGINAL_WIDTH
, cinfo
.image_width
);
340 image
->SetOption(wxIMAGE_OPTION_ORIGINAL_HEIGHT
, cinfo
.image_height
);
343 jpeg_finish_decompress( &cinfo
);
344 jpeg_destroy_decompress( &cinfo
);
349 struct jpeg_destination_mgr pub
;
351 wxOutputStream
*stream
;
353 } wx_destination_mgr
;
355 typedef wx_destination_mgr
* wx_dest_ptr
;
357 #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
362 CPP_METHODDEF(void) wx_init_destination (j_compress_ptr cinfo
)
364 wx_dest_ptr dest
= (wx_dest_ptr
) cinfo
->dest
;
366 /* Allocate the output buffer --- it will be released when done with image */
367 dest
->buffer
= (JOCTET
*)
368 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
369 OUTPUT_BUF_SIZE
* sizeof(JOCTET
));
370 dest
->pub
.next_output_byte
= dest
->buffer
;
371 dest
->pub
.free_in_buffer
= OUTPUT_BUF_SIZE
;
374 CPP_METHODDEF(wxjpeg_boolean
) wx_empty_output_buffer (j_compress_ptr cinfo
)
376 wx_dest_ptr dest
= (wx_dest_ptr
) cinfo
->dest
;
378 dest
->stream
->Write(dest
->buffer
, OUTPUT_BUF_SIZE
);
379 dest
->pub
.next_output_byte
= dest
->buffer
;
380 dest
->pub
.free_in_buffer
= OUTPUT_BUF_SIZE
;
384 CPP_METHODDEF(void) wx_term_destination (j_compress_ptr cinfo
)
386 wx_dest_ptr dest
= (wx_dest_ptr
) cinfo
->dest
;
387 size_t datacount
= OUTPUT_BUF_SIZE
- dest
->pub
.free_in_buffer
;
388 /* Write any data remaining in the buffer */
390 dest
->stream
->Write(dest
->buffer
, datacount
);
393 GLOBAL(void) wx_jpeg_io_dest (j_compress_ptr cinfo
, wxOutputStream
& outfile
)
397 if (cinfo
->dest
== NULL
) { /* first time for this JPEG object? */
398 cinfo
->dest
= (struct jpeg_destination_mgr
*)
399 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_PERMANENT
,
400 sizeof(wx_destination_mgr
));
403 dest
= (wx_dest_ptr
) cinfo
->dest
;
404 dest
->pub
.init_destination
= wx_init_destination
;
405 dest
->pub
.empty_output_buffer
= wx_empty_output_buffer
;
406 dest
->pub
.term_destination
= wx_term_destination
;
407 dest
->stream
= &outfile
;
412 bool wxJPEGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
414 struct jpeg_compress_struct cinfo
;
416 JSAMPROW row_pointer
[1]; /* pointer to JSAMPLE row[s] */
417 JSAMPLE
*image_buffer
;
418 int stride
; /* physical row width in image buffer */
420 cinfo
.err
= jpeg_std_error(&jerr
);
421 jerr
.error_exit
= wx_error_exit
;
424 cinfo
.err
->output_message
= wx_ignore_message
;
426 /* Establish the setjmp return context for wx_error_exit to use. */
427 if (setjmp(jerr
.setjmp_buffer
))
429 /* If we get here, the JPEG code has signaled an error.
430 * We need to clean up the JPEG object, close the input file, and return.
434 wxLogError(_("JPEG: Couldn't save image."));
436 jpeg_destroy_compress(&cinfo
);
440 jpeg_create_compress(&cinfo
);
441 wx_jpeg_io_dest(&cinfo
, stream
);
443 cinfo
.image_width
= image
->GetWidth();
444 cinfo
.image_height
= image
->GetHeight();
445 cinfo
.input_components
= 3;
446 cinfo
.in_color_space
= JCS_RGB
;
447 jpeg_set_defaults(&cinfo
);
449 // TODO: 3rd parameter is force_baseline, what value should this be?
450 // Code says: "If force_baseline is TRUE, the computed quantization table entries
451 // are limited to 1..255 for JPEG baseline compatibility."
452 // 'Quality' is a number between 0 (terrible) and 100 (very good).
453 // The default (in jcparam.c, jpeg_set_defaults) is 75,
454 // and force_baseline is TRUE.
455 if (image
->HasOption(wxIMAGE_OPTION_QUALITY
))
456 jpeg_set_quality(&cinfo
, image
->GetOptionInt(wxIMAGE_OPTION_QUALITY
), TRUE
);
458 // set the resolution fields in the output file
460 wxImageResolution res
= GetResolutionFromOptions(*image
, &resX
, &resY
);
461 if ( res
!= wxIMAGE_RESOLUTION_NONE
)
463 cinfo
.X_density
= resX
;
464 cinfo
.Y_density
= resY
;
466 // it so happens that wxIMAGE_RESOLUTION_INCHES/CM values are the same
467 // ones as used by libjpeg, so we can assign them directly
468 cinfo
.density_unit
= res
;
471 jpeg_start_compress(&cinfo
, TRUE
);
473 stride
= cinfo
.image_width
* 3; /* JSAMPLEs per row in image_buffer */
474 image_buffer
= image
->GetData();
475 while (cinfo
.next_scanline
< cinfo
.image_height
) {
476 row_pointer
[0] = &image_buffer
[cinfo
.next_scanline
* stride
];
477 jpeg_write_scanlines( &cinfo
, row_pointer
, 1 );
479 jpeg_finish_compress(&cinfo
);
480 jpeg_destroy_compress(&cinfo
);
486 #pragma warning(default:4611)
489 bool wxJPEGHandler::DoCanRead( wxInputStream
& stream
)
491 unsigned char hdr
[2];
493 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) ) // it's ok to modify the stream position here
496 return hdr
[0] == 0xFF && hdr
[1] == 0xD8;
499 #endif // wxUSE_STREAMS
501 /*static*/ wxVersionInfo
wxJPEGHandler::GetLibraryVersionInfo()
503 return wxVersionInfo("libjpeg", JPEG_LIB_VERSION
/10, JPEG_LIB_VERSION%10
);
506 #endif // wxUSE_LIBJPEG