]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/imagpng.cpp
don't define functions unused under CE when compiling for it (avoids warnings)
[wxWidgets.git] / src / common / imagpng.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/common/imagepng.cpp
3// Purpose: wxImage PNG handler
4// Author: Robert Roebling
5// RCS-ID: $Id$
6// Copyright: (c) Robert Roebling
7// Licence: wxWindows licence
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
15#pragma implementation "imagpng.h"
16#endif
17
18// ----------------------------------------------------------------------------
19// headers
20// ----------------------------------------------------------------------------
21
22// For compilers that support precompilation, includes "wx.h".
23#include "wx/wxprec.h"
24
25#ifdef __BORLANDC__
26 #pragma hdrstop
27#endif
28
29#ifndef WX_PRECOMP
30 #include "wx/defs.h"
31#endif
32
33#if wxUSE_IMAGE && wxUSE_LIBPNG
34
35#include "wx/imagpng.h"
36#include "wx/bitmap.h"
37#include "wx/debug.h"
38#include "wx/log.h"
39#include "wx/app.h"
40#include "png.h"
41#include "wx/filefn.h"
42#include "wx/wfstream.h"
43#include "wx/intl.h"
44#include "wx/module.h"
45
46// For memcpy
47#include <string.h>
48
49#ifdef __SALFORDC__
50#ifdef FAR
51#undef FAR
52#endif
53#endif
54
55// ----------------------------------------------------------------------------
56// constants
57// ----------------------------------------------------------------------------
58
59// image can not have any transparent pixels at all, have only 100% opaque
60// and/or 100% transparent pixels in which case a simple mask is enough to
61// store this information in wxImage or have a real alpha channel in which case
62// we need to have it in wxImage as well
63enum Transparency
64{
65 Transparency_None,
66 Transparency_Mask,
67 Transparency_Alpha
68};
69
70// ----------------------------------------------------------------------------
71// local functions
72// ----------------------------------------------------------------------------
73
74// return the kind of transparency needed for this image assuming that it does
75// have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
76static Transparency
77CheckTransparency(unsigned char **lines,
78 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
79 size_t numColBytes);
80
81// init the alpha channel for the image and fill it with 1s up to (x, y)
82static unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y);
83
84// find a free colour for the mask in the PNG data array
85static void
86FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
87 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask);
88
89// is the pixel with this value of alpha a fully opaque one?
90static inline
91bool IsOpaque(unsigned char a)
92{
93 return a == 0xff;
94}
95
96// is the pixel with this value of alpha a fully transparent one?
97static inline
98bool IsTransparent(unsigned char a)
99{
100 return !a;
101}
102
103// ============================================================================
104// wxPNGHandler implementation
105// ============================================================================
106
107IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler)
108
109#if wxUSE_STREAMS
110
111#ifndef PNGLINKAGEMODE
112 #ifdef __WATCOMC__
113 // we need an explicit cdecl for Watcom, at least according to
114 //
115 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
116 //
117 // more testing is needed for this however, please remove this comment
118 // if you can confirm that my fix works with Watcom 11
119 #define PNGLINKAGEMODE cdecl
120 #else
121 #define PNGLINKAGEMODE LINKAGEMODE
122 #endif
123#endif
124
125
126// VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
127// First, let me describe what's the problem: libpng uses jmp_buf in
128// its png_struct structure. Unfortunately, this structure is
129// compiler-specific and may vary in size, so if you use libpng compiled
130// as DLL with another compiler than the main executable, it may not work
131// (this is for example the case with wxMGL port and SciTech MGL library
132// that provides custom runtime-loadable libpng implementation with jmpbuf
133// disabled altogether). Luckily, it is still possible to use setjmp() &
134// longjmp() as long as the structure is not part of png_struct.
135//
136// Sadly, there's no clean way to attach user-defined data to png_struct.
137// There is only one customizable place, png_struct.io_ptr, which is meant
138// only for I/O routines and is set with png_set_read_fn or
139// png_set_write_fn. The hacky part is that we use io_ptr to store
140// a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
141
142struct wxPNGInfoStruct
143{
144 jmp_buf jmpbuf;
145 bool verbose;
146
147 union
148 {
149 wxInputStream *in;
150 wxOutputStream *out;
151 } stream;
152};
153
154#define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
155
156// ----------------------------------------------------------------------------
157// helper functions
158// ----------------------------------------------------------------------------
159
160extern "C"
161{
162
163void PNGLINKAGEMODE wx_PNG_stream_reader( png_structp png_ptr, png_bytep data,
164 png_size_t length )
165{
166 WX_PNG_INFO(png_ptr)->stream.in->Read(data, length);
167}
168
169void PNGLINKAGEMODE wx_PNG_stream_writer( png_structp png_ptr, png_bytep data,
170 png_size_t length )
171{
172 WX_PNG_INFO(png_ptr)->stream.out->Write(data, length);
173}
174
175// from pngerror.c
176// so that the libpng doesn't send anything on stderr
177void
178PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message)
179{
180 wxPNGInfoStruct *info = WX_PNG_INFO(png_ptr);
181 if (info->verbose)
182 wxLogError( wxString::FromAscii(message) );
183
184#ifdef USE_FAR_KEYWORD
185 {
186 jmp_buf jmpbuf;
187 png_memcpy(jmpbuf,info->jmpbuf,sizeof(jmp_buf));
188 longjmp(jmpbuf, 1);
189 }
190#else
191 longjmp(info->jmpbuf, 1);
192#endif
193}
194
195void
196PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message)
197{
198 wxPNGInfoStruct *info = WX_PNG_INFO(png_ptr);
199 if (info->verbose)
200 wxLogWarning( wxString::FromAscii(message) );
201}
202
203} // extern "C"
204
205// ----------------------------------------------------------------------------
206// LoadFile() helpers
207// ----------------------------------------------------------------------------
208
209// determine the kind of transparency we need for this image: if the only alpha
210// values it has are 0 (transparent) and 0xff (opaque) then we can simply
211// create a mask for it, we should be ok with a simple mask but otherwise we
212// need a full blown alpha channel in wxImage
213//
214// parameters:
215// lines raw PNG data
216// x, y starting position
217// w, h size of the image
218// numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
219// (NB: alpha always follows the colour bytes)
220Transparency
221CheckTransparency(unsigned char **lines,
222 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
223 size_t numColBytes)
224{
225 // suppose that a mask will suffice and check all the remaining alpha
226 // values to see if it does
227 for ( ; y < h; y++ )
228 {
229 // each pixel is numColBytes+1 bytes, offset into the current line by
230 // the current x position
231 unsigned const char *ptr = lines[y] + (x * (numColBytes + 1));
232
233 for ( png_uint_32 x2 = x; x2 < w; x2++ )
234 {
235 // skip the grey or colour byte(s)
236 ptr += numColBytes;
237
238 unsigned char a2 = *ptr++;
239
240 if ( !IsTransparent(a2) && !IsOpaque(a2) )
241 {
242 // not fully opaque nor fully transparent, hence need alpha
243 return Transparency_Alpha;
244 }
245 }
246
247 // during the next loop iteration check all the pixels in the row
248 x = 0;
249 }
250
251 // mask will be enough
252 return Transparency_Mask;
253}
254
255unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y)
256{
257 // create alpha channel
258 image->SetAlpha();
259
260 unsigned char *alpha = image->GetAlpha();
261
262 // set alpha for the pixels we had so far
263 png_uint_32 end = y * image->GetWidth() + x;
264 for ( png_uint_32 i = 0; i < end; i++ )
265 {
266 // all the previous pixels were opaque
267 *alpha++ = 0xff;
268 }
269
270 return alpha;
271}
272
273void
274FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
275 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask)
276{
277 // choosing the colour for the mask is more
278 // difficult: we need to iterate over the entire
279 // image for this in order to choose an unused
280 // colour (this is not very efficient but what else
281 // can we do?)
282 wxImageHistogram h;
283 unsigned nentries = 0;
284 unsigned char r2, g2, b2;
285 for ( png_uint_32 y2 = 0; y2 < height; y2++ )
286 {
287 const unsigned char *p = lines[y2];
288 for ( png_uint_32 x2 = 0; x2 < width; x2++ )
289 {
290 r2 = *p++;
291 g2 = *p++;
292 b2 = *p++;
293
294 wxImageHistogramEntry&
295 entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)];
296
297 if ( entry.value++ == 0 )
298 entry.index = nentries++;
299 }
300 }
301
302 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
303 {
304 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
305
306 // use a fixed mask colour and we'll fudge
307 // the real pixels with this colour (see
308 // below)
309 rMask = 0xfe;
310 gMask = 0;
311 bMask = 0xff;
312 }
313}
314
315// ----------------------------------------------------------------------------
316// reading PNGs
317// ----------------------------------------------------------------------------
318
319bool wxPNGHandler::DoCanRead( wxInputStream& stream )
320{
321 unsigned char hdr[4];
322
323 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
324 return FALSE;
325
326 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
327}
328
329// convert data from RGB to wxImage format
330static
331void CopyDataFromPNG(wxImage *image,
332 unsigned char **lines,
333 png_uint_32 width,
334 png_uint_32 height,
335 int color_type)
336{
337 Transparency transparency = Transparency_None;
338
339 // only non NULL if transparency == Transparency_Alpha
340 unsigned char *alpha = NULL;
341
342 // RGB of the mask colour if transparency == Transparency_Mask
343 // (but init them anyhow to avoid compiler warnings)
344 unsigned char rMask = 0,
345 gMask = 0,
346 bMask = 0;
347
348 unsigned char *ptrDst = image->GetData();
349 if ( !(color_type & PNG_COLOR_MASK_COLOR) )
350 {
351 // grey image: GAGAGA... where G == grey component and A == alpha
352 for ( png_uint_32 y = 0; y < height; y++ )
353 {
354 const unsigned char *ptrSrc = lines[y];
355 for ( png_uint_32 x = 0; x < width; x++ )
356 {
357 unsigned char g = *ptrSrc++;
358 unsigned char a = *ptrSrc++;
359
360 // the first time we encounter a transparent pixel we must
361 // decide about what to do about them
362 if ( !IsOpaque(a) && transparency == Transparency_None )
363 {
364 // we'll need at least the mask for this image and
365 // maybe even full alpha channel info: the former is
366 // only enough if we have alpha values of 0 and 0xff
367 // only, otherwisewe need the latter
368 transparency = CheckTransparency
369 (
370 lines,
371 x, y,
372 width, height,
373 1
374 );
375
376 if ( transparency == Transparency_Mask )
377 {
378 // let's choose this colour for the mask: this is
379 // not a problem here as all the other pixels are
380 // grey, i.e. R == G == B which is not the case for
381 // this one so no confusion is possible
382 rMask = 0xff;
383 gMask = 0;
384 bMask = 0xff;
385 }
386 else // transparency == Transparency_Alpha
387 {
388 alpha = InitAlpha(image, x, y);
389 }
390 }
391
392 switch ( transparency )
393 {
394 case Transparency_Mask:
395 if ( IsTransparent(a) )
396 {
397 *ptrDst++ = rMask;
398 *ptrDst++ = bMask;
399 *ptrDst++ = gMask;
400 break;
401 }
402 // else: !transparent
403
404 // must be opaque then as otherwise we shouldn't be
405 // using the mask at all
406 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
407
408 // fall through
409
410 case Transparency_Alpha:
411 if ( alpha )
412 *alpha++ = a;
413 // fall through
414
415 case Transparency_None:
416 *ptrDst++ = g;
417 *ptrDst++ = g;
418 *ptrDst++ = g;
419 break;
420 }
421 }
422 }
423 }
424 else // colour image: RGBRGB...
425 {
426 for ( png_uint_32 y = 0; y < height; y++ )
427 {
428 const unsigned char *ptrSrc = lines[y];
429 for ( png_uint_32 x = 0; x < width; x++ )
430 {
431 unsigned char r = *ptrSrc++;
432 unsigned char g = *ptrSrc++;
433 unsigned char b = *ptrSrc++;
434 unsigned char a = *ptrSrc++;
435
436 // the logic here is the same as for the grey case except
437 // where noted
438 if ( !IsOpaque(a) && transparency == Transparency_None )
439 {
440 transparency = CheckTransparency
441 (
442 lines,
443 x, y,
444 width, height,
445 3
446 );
447
448 if ( transparency == Transparency_Mask )
449 {
450 FindMaskColour(lines, width, height,
451 rMask, gMask, bMask);
452 }
453 else // transparency == Transparency_Alpha
454 {
455 alpha = InitAlpha(image, x, y);
456 }
457
458 }
459
460 switch ( transparency )
461 {
462 case Transparency_Mask:
463 if ( IsTransparent(a) )
464 {
465 *ptrDst++ = rMask;
466 *ptrDst++ = bMask;
467 *ptrDst++ = gMask;
468 break;
469 }
470 else // !transparent
471 {
472 // must be opaque then as otherwise we shouldn't be
473 // using the mask at all
474 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
475
476 // if we couldn't find a unique colour for the
477 // mask, we can have real pixels with the same
478 // value as the mask and it's better to slightly
479 // change their colour than to make them
480 // transparent
481 if ( r == rMask && g == gMask && b == bMask )
482 {
483 r++;
484 }
485 }
486
487 // fall through
488
489 case Transparency_Alpha:
490 if ( alpha )
491 *alpha++ = a;
492 // fall through
493
494 case Transparency_None:
495 *ptrDst++ = r;
496 *ptrDst++ = g;
497 *ptrDst++ = b;
498 break;
499 }
500 }
501 }
502 }
503
504 if ( transparency == Transparency_Mask )
505 {
506 image->SetMaskColour(rMask, gMask, bMask);
507 }
508}
509
510// temporarily disable the warning C4611 (interaction between '_setjmp' and
511// C++ object destruction is non-portable) - I don't see any dtors here
512#ifdef __VISUALC__
513 #pragma warning(disable:4611)
514#endif /* VC++ */
515
516bool
517wxPNGHandler::LoadFile(wxImage *image,
518 wxInputStream& stream,
519 bool verbose,
520 int WXUNUSED(index))
521{
522 // VZ: as this function uses setjmp() the only fool proof error handling
523 // method is to use goto (setjmp is not really C++ dtors friendly...)
524
525 unsigned char **lines = NULL;
526 png_infop info_ptr = (png_infop) NULL;
527 wxPNGInfoStruct wxinfo;
528
529 wxinfo.verbose = verbose;
530 wxinfo.stream.in = &stream;
531
532 image->Destroy();
533
534 png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING,
535 (voidp) NULL,
536 (png_error_ptr) NULL,
537 (png_error_ptr) NULL );
538 if (!png_ptr)
539 goto error;
540
541 png_set_error_fn(png_ptr, (png_voidp)NULL, wx_png_error, wx_png_warning);
542
543 // NB: please see the comment near wxPNGInfoStruct declaration for
544 // explanation why this line is mandatory
545 png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader);
546
547 info_ptr = png_create_info_struct( png_ptr );
548 if (!info_ptr)
549 goto error;
550
551 if (setjmp(wxinfo.jmpbuf))
552 goto error;
553
554 png_uint_32 i, width, height;
555 int bit_depth, color_type, interlace_type;
556
557 png_read_info( png_ptr, info_ptr );
558 png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, (int*) NULL, (int*) NULL );
559
560 if (color_type == PNG_COLOR_TYPE_PALETTE)
561 png_set_expand( png_ptr );
562
563 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
564 if (bit_depth < 8)
565 png_set_expand( png_ptr );
566
567 png_set_strip_16( png_ptr );
568 png_set_packing( png_ptr );
569 if (png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS))
570 png_set_expand( png_ptr );
571 png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER );
572
573 image->Create( (int)width, (int)height );
574
575 if (!image->Ok())
576 goto error;
577
578 lines = (unsigned char **)malloc( (size_t)(height * sizeof(unsigned char *)) );
579 if ( !lines )
580 goto error;
581
582 for (i = 0; i < height; i++)
583 {
584 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
585 {
586 for ( unsigned int n = 0; n < i; n++ )
587 free( lines[n] );
588 goto error;
589 }
590 }
591
592 png_read_image( png_ptr, lines );
593 png_read_end( png_ptr, info_ptr );
594 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
595
596 // loaded successfully, now init wxImage with this data
597 CopyDataFromPNG(image, lines, width, height, color_type);
598
599 for ( i = 0; i < height; i++ )
600 free( lines[i] );
601 free( lines );
602
603 return TRUE;
604
605error:
606 if (verbose)
607 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
608
609 if ( image->Ok() )
610 {
611 image->Destroy();
612 }
613
614 if ( lines )
615 {
616 free( lines );
617 }
618
619 if ( png_ptr )
620 {
621 if ( info_ptr )
622 {
623 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
624 free(info_ptr);
625 }
626 else
627 png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL );
628 }
629 return FALSE;
630}
631
632// ----------------------------------------------------------------------------
633// writing PNGs
634// ----------------------------------------------------------------------------
635
636bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
637{
638 wxPNGInfoStruct wxinfo;
639
640 wxinfo.verbose = verbose;
641 wxinfo.stream.out = &stream;
642
643 png_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
644 if (!png_ptr)
645 {
646 if (verbose)
647 wxLogError(_("Couldn't save PNG image."));
648 return FALSE;
649 }
650
651 png_set_error_fn(png_ptr, (png_voidp)NULL, wx_png_error, wx_png_warning);
652
653 png_infop info_ptr = png_create_info_struct(png_ptr);
654 if (info_ptr == NULL)
655 {
656 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
657 if (verbose)
658 wxLogError(_("Couldn't save PNG image."));
659 return FALSE;
660 }
661
662 if (setjmp(wxinfo.jmpbuf))
663 {
664 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
665 if (verbose)
666 wxLogError(_("Couldn't save PNG image."));
667 return FALSE;
668 }
669
670 // NB: please see the comment near wxPNGInfoStruct declaration for
671 // explanation why this line is mandatory
672 png_set_write_fn( png_ptr, &wxinfo, wx_PNG_stream_writer, NULL);
673
674 png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(), 8,
675 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
676 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
677
678 png_color_8 sig_bit;
679 sig_bit.red = 8;
680 sig_bit.green = 8;
681 sig_bit.blue = 8;
682 sig_bit.alpha = 8;
683 png_set_sBIT( png_ptr, info_ptr, &sig_bit );
684 png_write_info( png_ptr, info_ptr );
685 png_set_shift( png_ptr, &sig_bit );
686 png_set_packing( png_ptr );
687
688 unsigned char *data = (unsigned char *)malloc( image->GetWidth()*4 );
689 if (!data)
690 {
691 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
692 return FALSE;
693 }
694
695 for (int y = 0; y < image->GetHeight(); y++)
696 {
697 unsigned char *ptr = image->GetData() + (y * image->GetWidth() * 3);
698 for (int x = 0; x < image->GetWidth(); x++)
699 {
700 data[(x << 2) + 0] = *ptr++;
701 data[(x << 2) + 1] = *ptr++;
702 data[(x << 2) + 2] = *ptr++;
703 if (( !image->HasMask() ) || \
704 (data[(x << 2) + 0] != image->GetMaskRed()) || \
705 (data[(x << 2) + 1] != image->GetMaskGreen()) || \
706 (data[(x << 2) + 2] != image->GetMaskBlue()))
707 {
708 data[(x << 2) + 3] = 255;
709 }
710 else
711 {
712 data[(x << 2) + 3] = 0;
713 }
714 }
715 png_bytep row_ptr = data;
716 png_write_rows( png_ptr, &row_ptr, 1 );
717 }
718
719 free(data);
720 png_write_end( png_ptr, info_ptr );
721 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
722
723 return TRUE;
724}
725
726#ifdef __VISUALC__
727 #pragma warning(default:4611)
728#endif /* VC++ */
729
730#endif // wxUSE_STREAMS
731
732#endif // wxUSE_LIBPNG