1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagepng.cpp
3 // Purpose: wxImage PNG handler
4 // Author: Robert Roebling
6 // Copyright: (c) Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // ============================================================================
12 // ============================================================================
14 // ----------------------------------------------------------------------------
16 // ----------------------------------------------------------------------------
18 // For compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
25 #if wxUSE_IMAGE && wxUSE_LIBPNG
27 #include "wx/imagpng.h"
32 #include "wx/bitmap.h"
33 #include "wx/module.h"
37 #include "wx/filefn.h"
38 #include "wx/wfstream.h"
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 // image can not have any transparent pixels at all, have only 100% opaque
55 // and/or 100% transparent pixels in which case a simple mask is enough to
56 // store this information in wxImage or have a real alpha channel in which case
57 // we need to have it in wxImage as well
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // return the kind of transparency needed for this image assuming that it does
70 // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
72 CheckTransparency(unsigned char **lines
,
73 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
76 // init the alpha channel for the image and fill it with 1s up to (x, y)
77 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
79 // find a free colour for the mask in the PNG data array
81 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
82 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
84 // is the pixel with this value of alpha a fully opaque one?
86 bool IsOpaque(unsigned char a
)
91 // is the pixel with this value of alpha a fully transparent one?
93 bool IsTransparent(unsigned char a
)
98 // ============================================================================
99 // wxPNGHandler implementation
100 // ============================================================================
102 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
106 #ifndef PNGLINKAGEMODE
107 #if defined(__WATCOMC__) && ( defined(__WXMSW__) || defined(__WXMGL__) )
108 // we need an explicit cdecl for Watcom, at least according to
110 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
112 // more testing is needed for this however, please remove this comment
113 // if you can confirm that my fix works with Watcom 11
114 #define PNGLINKAGEMODE cdecl
116 #define PNGLINKAGEMODE LINKAGEMODE
121 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
122 // First, let me describe what's the problem: libpng uses jmp_buf in
123 // its png_struct structure. Unfortunately, this structure is
124 // compiler-specific and may vary in size, so if you use libpng compiled
125 // as DLL with another compiler than the main executable, it may not work
126 // (this is for example the case with wxMGL port and SciTech MGL library
127 // that provides custom runtime-loadable libpng implementation with jmpbuf
128 // disabled altogether). Luckily, it is still possible to use setjmp() &
129 // longjmp() as long as the structure is not part of png_struct.
131 // Sadly, there's no clean way to attach user-defined data to png_struct.
132 // There is only one customizable place, png_struct.io_ptr, which is meant
133 // only for I/O routines and is set with png_set_read_fn or
134 // png_set_write_fn. The hacky part is that we use io_ptr to store
135 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
137 struct wxPNGInfoStruct
149 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
158 void PNGLINKAGEMODE
wx_PNG_stream_reader( png_structp png_ptr
, png_bytep data
,
161 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
164 void PNGLINKAGEMODE
wx_PNG_stream_writer( png_structp png_ptr
, png_bytep data
,
167 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
171 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
173 wxPNGInfoStruct
*info
= png_ptr
? WX_PNG_INFO(png_ptr
) : NULL
;
174 if ( !info
|| info
->verbose
)
175 wxLogWarning( wxString::FromAscii(message
) );
179 // so that the libpng doesn't send anything on stderr
181 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
183 wx_png_warning(NULL
, message
);
185 // we're not using libpng built-in jump buffer (see comment before
186 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
188 longjmp(WX_PNG_INFO(png_ptr
)->jmpbuf
, 1);
193 // ----------------------------------------------------------------------------
194 // LoadFile() helpers
195 // ----------------------------------------------------------------------------
197 // determine the kind of transparency we need for this image: if the only alpha
198 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
199 // create a mask for it, we should be ok with a simple mask but otherwise we
200 // need a full blown alpha channel in wxImage
203 // lines raw PNG data
204 // x, y starting position
205 // w, h size of the image
206 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
207 // (NB: alpha always follows the colour bytes)
209 CheckTransparency(unsigned char **lines
,
210 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
213 // suppose that a mask will suffice and check all the remaining alpha
214 // values to see if it does
217 // each pixel is numColBytes+1 bytes, offset into the current line by
218 // the current x position
219 unsigned const char *ptr
= lines
[y
] + (x
* (numColBytes
+ 1));
221 for ( png_uint_32 x2
= x
; x2
< w
; x2
++ )
223 // skip the grey or colour byte(s)
226 unsigned char a2
= *ptr
++;
228 if ( !IsTransparent(a2
) && !IsOpaque(a2
) )
230 // not fully opaque nor fully transparent, hence need alpha
231 return Transparency_Alpha
;
235 // during the next loop iteration check all the pixels in the row
239 // mask will be enough
240 return Transparency_Mask
;
243 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
245 // create alpha channel
248 unsigned char *alpha
= image
->GetAlpha();
250 // set alpha for the pixels we had so far
251 png_uint_32 end
= y
* image
->GetWidth() + x
;
252 for ( png_uint_32 i
= 0; i
< end
; i
++ )
254 // all the previous pixels were opaque
262 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
263 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
265 // choosing the colour for the mask is more
266 // difficult: we need to iterate over the entire
267 // image for this in order to choose an unused
268 // colour (this is not very efficient but what else
271 unsigned nentries
= 0;
272 unsigned char r2
, g2
, b2
;
273 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
275 const unsigned char *p
= lines
[y2
];
276 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
282 wxImageHistogramEntry
&
283 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
285 if ( entry
.value
++ == 0 )
286 entry
.index
= nentries
++;
290 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
292 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
294 // use a fixed mask colour and we'll fudge
295 // the real pixels with this colour (see
303 // ----------------------------------------------------------------------------
305 // ----------------------------------------------------------------------------
307 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
309 unsigned char hdr
[4];
311 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
314 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
317 // convert data from RGB to wxImage format
319 void CopyDataFromPNG(wxImage
*image
,
320 unsigned char **lines
,
325 Transparency transparency
= Transparency_None
;
327 // only non NULL if transparency == Transparency_Alpha
328 unsigned char *alpha
= NULL
;
330 // RGB of the mask colour if transparency == Transparency_Mask
331 // (but init them anyhow to avoid compiler warnings)
332 unsigned char rMask
= 0,
336 unsigned char *ptrDst
= image
->GetData();
337 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
339 // grey image: GAGAGA... where G == grey component and A == alpha
340 for ( png_uint_32 y
= 0; y
< height
; y
++ )
342 const unsigned char *ptrSrc
= lines
[y
];
343 for ( png_uint_32 x
= 0; x
< width
; x
++ )
345 unsigned char g
= *ptrSrc
++;
346 unsigned char a
= *ptrSrc
++;
348 // the first time we encounter a transparent pixel we must
349 // decide about what to do about them
350 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
352 // we'll need at least the mask for this image and
353 // maybe even full alpha channel info: the former is
354 // only enough if we have alpha values of 0 and 0xff
355 // only, otherwisewe need the latter
356 transparency
= CheckTransparency
364 if ( transparency
== Transparency_Mask
)
366 // let's choose this colour for the mask: this is
367 // not a problem here as all the other pixels are
368 // grey, i.e. R == G == B which is not the case for
369 // this one so no confusion is possible
374 else // transparency == Transparency_Alpha
376 alpha
= InitAlpha(image
, x
, y
);
380 switch ( transparency
)
382 case Transparency_Mask
:
383 if ( IsTransparent(a
) )
390 // else: !transparent
392 // must be opaque then as otherwise we shouldn't be
393 // using the mask at all
394 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
398 case Transparency_Alpha
:
403 case Transparency_None
:
412 else // colour image: RGBRGB...
414 for ( png_uint_32 y
= 0; y
< height
; y
++ )
416 const unsigned char *ptrSrc
= lines
[y
];
417 for ( png_uint_32 x
= 0; x
< width
; x
++ )
419 unsigned char r
= *ptrSrc
++;
420 unsigned char g
= *ptrSrc
++;
421 unsigned char b
= *ptrSrc
++;
422 unsigned char a
= *ptrSrc
++;
424 // the logic here is the same as for the grey case except
426 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
428 transparency
= CheckTransparency
436 if ( transparency
== Transparency_Mask
)
438 FindMaskColour(lines
, width
, height
,
439 rMask
, gMask
, bMask
);
441 else // transparency == Transparency_Alpha
443 alpha
= InitAlpha(image
, x
, y
);
448 switch ( transparency
)
450 case Transparency_Mask
:
451 if ( IsTransparent(a
) )
460 // must be opaque then as otherwise we shouldn't be
461 // using the mask at all
462 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
464 // if we couldn't find a unique colour for the
465 // mask, we can have real pixels with the same
466 // value as the mask and it's better to slightly
467 // change their colour than to make them
469 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
477 case Transparency_Alpha
:
482 case Transparency_None
:
492 if ( transparency
== Transparency_Mask
)
494 image
->SetMaskColour(rMask
, gMask
, bMask
);
498 // temporarily disable the warning C4611 (interaction between '_setjmp' and
499 // C++ object destruction is non-portable) - I don't see any dtors here
501 #pragma warning(disable:4611)
505 wxPNGHandler::LoadFile(wxImage
*image
,
506 wxInputStream
& stream
,
510 // VZ: as this function uses setjmp() the only fool-proof error handling
511 // method is to use goto (setjmp is not really C++ dtors friendly...)
513 unsigned char **lines
= NULL
;
514 png_infop info_ptr
= (png_infop
) NULL
;
515 wxPNGInfoStruct wxinfo
;
517 png_uint_32 i
, width
, height
= 0;
518 int bit_depth
, color_type
, interlace_type
;
520 wxinfo
.verbose
= verbose
;
521 wxinfo
.stream
.in
= &stream
;
525 png_structp png_ptr
= png_create_read_struct
527 PNG_LIBPNG_VER_STRING
,
535 // NB: please see the comment near wxPNGInfoStruct declaration for
536 // explanation why this line is mandatory
537 png_set_read_fn( png_ptr
, &wxinfo
, wx_PNG_stream_reader
);
539 info_ptr
= png_create_info_struct( png_ptr
);
543 if (setjmp(wxinfo
.jmpbuf
))
546 png_read_info( png_ptr
, info_ptr
);
547 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
549 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
550 png_set_expand( png_ptr
);
552 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
554 png_set_expand( png_ptr
);
556 png_set_strip_16( png_ptr
);
557 png_set_packing( png_ptr
);
558 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
559 png_set_expand( png_ptr
);
560 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
562 image
->Create((int)width
, (int)height
, (bool) false /* no need to init pixels */);
567 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
571 for (i
= 0; i
< height
; i
++)
573 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
575 for ( unsigned int n
= 0; n
< i
; n
++ )
581 png_read_image( png_ptr
, lines
);
582 png_read_end( png_ptr
, info_ptr
);
583 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
585 // loaded successfully, now init wxImage with this data
586 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
588 for ( i
= 0; i
< height
; i
++ )
596 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
605 for ( unsigned int n
= 0; n
< height
; n
++ )
615 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
619 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
624 // ----------------------------------------------------------------------------
626 // ----------------------------------------------------------------------------
628 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
630 wxPNGInfoStruct wxinfo
;
632 wxinfo
.verbose
= verbose
;
633 wxinfo
.stream
.out
= &stream
;
635 png_structp png_ptr
= png_create_write_struct
637 PNG_LIBPNG_VER_STRING
,
645 wxLogError(_("Couldn't save PNG image."));
649 png_infop info_ptr
= png_create_info_struct(png_ptr
);
650 if (info_ptr
== NULL
)
652 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
654 wxLogError(_("Couldn't save PNG image."));
658 if (setjmp(wxinfo
.jmpbuf
))
660 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
662 wxLogError(_("Couldn't save PNG image."));
666 // NB: please see the comment near wxPNGInfoStruct declaration for
667 // explanation why this line is mandatory
668 png_set_write_fn( png_ptr
, &wxinfo
, wx_PNG_stream_writer
, NULL
);
670 const int iColorType
= image
->HasOption(wxIMAGE_OPTION_PNG_FORMAT
)
671 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT
)
673 const int iBitDepth
= image
->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH
)
674 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH
)
677 wxASSERT_MSG( iBitDepth
== 8 || iBitDepth
== 16,
678 _T("PNG bit depth must be 8 or 16") );
680 bool bHasAlpha
= image
->HasAlpha();
681 bool bHasMask
= image
->HasMask();
682 bool bUseAlpha
= bHasAlpha
|| bHasMask
;
685 if ( iColorType
==wxPNG_TYPE_COLOUR
)
687 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_RGB_ALPHA
688 : PNG_COLOR_TYPE_RGB
;
692 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_GRAY_ALPHA
693 : PNG_COLOR_TYPE_GRAY
;
696 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(),
697 iBitDepth
, iPngColorType
,
698 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_BASE
,
699 PNG_FILTER_TYPE_BASE
);
704 if ( iPngColorType
& PNG_COLOR_MASK_COLOR
)
708 sig_bit
.blue
= (png_byte
)iBitDepth
;
713 sig_bit
.gray
= (png_byte
)iBitDepth
;
717 if ( iPngColorType
& PNG_COLOR_MASK_ALPHA
)
719 sig_bit
.alpha
= (png_byte
)iBitDepth
;
723 if ( iBitDepth
== 16 )
726 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
727 png_write_info( png_ptr
, info_ptr
);
728 png_set_shift( png_ptr
, &sig_bit
);
729 png_set_packing( png_ptr
);
732 data
= (unsigned char *)malloc( image
->GetWidth() * iElements
);
735 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
740 pAlpha
= (unsigned char *)(bHasAlpha
? image
->GetAlpha() : NULL
);
741 int iHeight
= image
->GetHeight();
742 int iWidth
= image
->GetWidth();
744 unsigned char uchMaskRed
= 0, uchMaskGreen
= 0, uchMaskBlue
= 0;
748 uchMaskRed
= image
->GetMaskRed();
749 uchMaskGreen
= image
->GetMaskGreen();
750 uchMaskBlue
= image
->GetMaskBlue();
753 unsigned char *pColors
= image
->GetData();
755 for (int y
= 0; y
!= iHeight
; ++y
)
757 unsigned char *pData
= data
;
758 for (int x
= 0; x
!= iWidth
; x
++)
760 unsigned char uchRed
= *pColors
++;
761 unsigned char uchGreen
= *pColors
++;
762 unsigned char uchBlue
= *pColors
++;
764 switch ( iColorType
)
767 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
770 case wxPNG_TYPE_COLOUR
:
772 if ( iBitDepth
== 16 )
775 if ( iBitDepth
== 16 )
778 if ( iBitDepth
== 16 )
782 case wxPNG_TYPE_GREY
:
784 // where do these coefficients come from? maybe we
785 // should have image options for them as well?
787 (unsigned) (76.544*(unsigned)uchRed
+
788 150.272*(unsigned)uchGreen
+
789 36.864*(unsigned)uchBlue
);
791 *pData
++ = (unsigned char)((uiColor
>> 8) & 0xFF);
792 if ( iBitDepth
== 16 )
793 *pData
++ = (unsigned char)(uiColor
& 0xFF);
797 case wxPNG_TYPE_GREY_RED
:
799 if ( iBitDepth
== 16 )
806 unsigned char uchAlpha
= 255;
808 uchAlpha
= *pAlpha
++;
812 if ( (uchRed
== uchMaskRed
)
813 && (uchGreen
== uchMaskGreen
)
814 && (uchBlue
== uchMaskBlue
) )
819 if ( iBitDepth
== 16 )
824 png_bytep row_ptr
= data
;
825 png_write_rows( png_ptr
, &row_ptr
, 1 );
829 png_write_end( png_ptr
, info_ptr
);
830 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
836 #pragma warning(default:4611)
839 #endif // wxUSE_STREAMS
841 #endif // wxUSE_LIBPNG