1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagpng.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/palette.h"
33 #include "wx/stream.h"
41 // ----------------------------------------------------------------------------
43 // ----------------------------------------------------------------------------
45 // image can not have any transparent pixels at all, have only 100% opaque
46 // and/or 100% transparent pixels in which case a simple mask is enough to
47 // store this information in wxImage or have a real alpha channel in which case
48 // we need to have it in wxImage as well
56 // ----------------------------------------------------------------------------
58 // ----------------------------------------------------------------------------
60 // return the kind of transparency needed for this image assuming that it does
61 // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
63 CheckTransparency(unsigned char **lines
,
64 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
67 // init the alpha channel for the image and fill it with 1s up to (x, y)
68 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
70 // find a free colour for the mask in the PNG data array
72 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
73 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
75 // is the pixel with this value of alpha a fully opaque one?
77 bool IsOpaque(unsigned char a
)
82 // is the pixel with this value of alpha a fully transparent one?
84 bool IsTransparent(unsigned char a
)
89 // ============================================================================
90 // wxPNGHandler implementation
91 // ============================================================================
93 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
97 #ifndef PNGLINKAGEMODE
99 #define PNGLINKAGEMODE PNGAPI
100 #elif defined(__WATCOMC__)
101 // we need an explicit cdecl for Watcom, at least according to
103 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
105 // more testing is needed for this however, please remove this comment
106 // if you can confirm that my fix works with Watcom 11
107 #define PNGLINKAGEMODE cdecl
109 #define PNGLINKAGEMODE LINKAGEMODE
114 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
115 // First, let me describe what's the problem: libpng uses jmp_buf in
116 // its png_struct structure. Unfortunately, this structure is
117 // compiler-specific and may vary in size, so if you use libpng compiled
118 // as DLL with another compiler than the main executable, it may not work
119 // (this is for example the case with wxMGL port and SciTech MGL library
120 // that provides custom runtime-loadable libpng implementation with jmpbuf
121 // disabled altogether). Luckily, it is still possible to use setjmp() &
122 // longjmp() as long as the structure is not part of png_struct.
124 // Sadly, there's no clean way to attach user-defined data to png_struct.
125 // There is only one customizable place, png_struct.io_ptr, which is meant
126 // only for I/O routines and is set with png_set_read_fn or
127 // png_set_write_fn. The hacky part is that we use io_ptr to store
128 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
130 struct wxPNGInfoStruct
142 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
151 static void PNGLINKAGEMODE
wx_PNG_stream_reader( png_structp png_ptr
, png_bytep data
,
154 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
157 static void PNGLINKAGEMODE
wx_PNG_stream_writer( png_structp png_ptr
, png_bytep data
,
160 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
164 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
166 wxPNGInfoStruct
*info
= png_ptr
? WX_PNG_INFO(png_ptr
) : NULL
;
167 if ( !info
|| info
->verbose
)
169 wxLogWarning( wxString::FromAscii(message
) );
174 // so that the libpng doesn't send anything on stderr
176 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
178 wx_png_warning(NULL
, message
);
180 // we're not using libpng built-in jump buffer (see comment before
181 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
183 longjmp(WX_PNG_INFO(png_ptr
)->jmpbuf
, 1);
188 // ----------------------------------------------------------------------------
189 // LoadFile() helpers
190 // ----------------------------------------------------------------------------
192 // determine the kind of transparency we need for this image: if the only alpha
193 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
194 // create a mask for it, we should be ok with a simple mask but otherwise we
195 // need a full blown alpha channel in wxImage
198 // lines raw PNG data
199 // x, y starting position
200 // w, h size of the image
201 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
202 // (NB: alpha always follows the colour bytes)
204 CheckTransparency(unsigned char **lines
,
205 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
208 // suppose that a mask will suffice and check all the remaining alpha
209 // values to see if it does
212 // each pixel is numColBytes+1 bytes, offset into the current line by
213 // the current x position
214 unsigned const char *ptr
= lines
[y
] + (x
* (numColBytes
+ 1));
216 for ( png_uint_32 x2
= x
; x2
< w
; x2
++ )
218 // skip the grey or colour byte(s)
221 unsigned char a2
= *ptr
++;
223 if ( !IsTransparent(a2
) && !IsOpaque(a2
) )
225 // not fully opaque nor fully transparent, hence need alpha
226 return Transparency_Alpha
;
230 // during the next loop iteration check all the pixels in the row
234 // mask will be enough
235 return Transparency_Mask
;
238 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
240 // create alpha channel
243 unsigned char *alpha
= image
->GetAlpha();
245 // set alpha for the pixels we had so far
246 png_uint_32 end
= y
* image
->GetWidth() + x
;
247 for ( png_uint_32 i
= 0; i
< end
; i
++ )
249 // all the previous pixels were opaque
257 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
258 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
260 // choosing the colour for the mask is more
261 // difficult: we need to iterate over the entire
262 // image for this in order to choose an unused
263 // colour (this is not very efficient but what else
266 unsigned nentries
= 0;
267 unsigned char r2
, g2
, b2
;
268 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
270 const unsigned char *p
= lines
[y2
];
271 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
276 ++p
; // jump over alpha
278 wxImageHistogramEntry
&
279 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
281 if ( entry
.value
++ == 0 )
282 entry
.index
= nentries
++;
286 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
288 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
290 // use a fixed mask colour and we'll fudge
291 // the real pixels with this colour (see
299 // ----------------------------------------------------------------------------
301 // ----------------------------------------------------------------------------
303 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
305 unsigned char hdr
[4];
307 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) ) // it's ok to modify the stream position here
310 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
313 // convert data from RGB to wxImage format
315 void CopyDataFromPNG(wxImage
*image
,
316 unsigned char **lines
,
321 Transparency transparency
= Transparency_None
;
323 // only non NULL if transparency == Transparency_Alpha
324 unsigned char *alpha
= NULL
;
326 // RGB of the mask colour if transparency == Transparency_Mask
327 // (but init them anyhow to avoid compiler warnings)
328 unsigned char rMask
= 0,
332 unsigned char *ptrDst
= image
->GetData();
333 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
335 // grey image: GAGAGA... where G == grey component and A == alpha
336 for ( png_uint_32 y
= 0; y
< height
; y
++ )
338 const unsigned char *ptrSrc
= lines
[y
];
339 for ( png_uint_32 x
= 0; x
< width
; x
++ )
341 unsigned char g
= *ptrSrc
++;
342 unsigned char a
= *ptrSrc
++;
344 // the first time we encounter a transparent pixel we must
345 // decide about what to do about them
346 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
348 // we'll need at least the mask for this image and
349 // maybe even full alpha channel info: the former is
350 // only enough if we have alpha values of 0 and 0xff
351 // only, otherwisewe need the latter
352 transparency
= CheckTransparency
360 if ( transparency
== Transparency_Mask
)
362 // let's choose this colour for the mask: this is
363 // not a problem here as all the other pixels are
364 // grey, i.e. R == G == B which is not the case for
365 // this one so no confusion is possible
370 else // transparency == Transparency_Alpha
372 alpha
= InitAlpha(image
, x
, y
);
376 switch ( transparency
)
378 case Transparency_Mask
:
379 if ( IsTransparent(a
) )
386 // else: !transparent
388 // must be opaque then as otherwise we shouldn't be
389 // using the mask at all
390 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
394 case Transparency_Alpha
:
399 case Transparency_None
:
408 else // colour image: RGBRGB...
410 for ( png_uint_32 y
= 0; y
< height
; y
++ )
412 const unsigned char *ptrSrc
= lines
[y
];
413 for ( png_uint_32 x
= 0; x
< width
; x
++ )
415 unsigned char r
= *ptrSrc
++;
416 unsigned char g
= *ptrSrc
++;
417 unsigned char b
= *ptrSrc
++;
418 unsigned char a
= *ptrSrc
++;
420 // the logic here is the same as for the grey case except
422 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
424 transparency
= CheckTransparency
432 if ( transparency
== Transparency_Mask
)
434 FindMaskColour(lines
, width
, height
,
435 rMask
, gMask
, bMask
);
437 else // transparency == Transparency_Alpha
439 alpha
= InitAlpha(image
, x
, y
);
444 switch ( transparency
)
446 case Transparency_Mask
:
447 if ( IsTransparent(a
) )
456 // must be opaque then as otherwise we shouldn't be
457 // using the mask at all
458 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
460 // if we couldn't find a unique colour for the
461 // mask, we can have real pixels with the same
462 // value as the mask and it's better to slightly
463 // change their colour than to make them
465 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
473 case Transparency_Alpha
:
478 case Transparency_None
:
488 if ( transparency
== Transparency_Mask
)
490 image
->SetMaskColour(rMask
, gMask
, bMask
);
494 // temporarily disable the warning C4611 (interaction between '_setjmp' and
495 // C++ object destruction is non-portable) - I don't see any dtors here
497 #pragma warning(disable:4611)
501 wxPNGHandler::LoadFile(wxImage
*image
,
502 wxInputStream
& stream
,
506 // VZ: as this function uses setjmp() the only fool-proof error handling
507 // method is to use goto (setjmp is not really C++ dtors friendly...)
509 unsigned char **lines
= NULL
;
510 png_infop info_ptr
= (png_infop
) NULL
;
511 wxPNGInfoStruct wxinfo
;
513 png_uint_32 i
, width
, height
= 0;
514 int bit_depth
, color_type
, interlace_type
;
516 wxinfo
.verbose
= verbose
;
517 wxinfo
.stream
.in
= &stream
;
521 png_structp png_ptr
= png_create_read_struct
523 PNG_LIBPNG_VER_STRING
,
531 // NB: please see the comment near wxPNGInfoStruct declaration for
532 // explanation why this line is mandatory
533 png_set_read_fn( png_ptr
, &wxinfo
, wx_PNG_stream_reader
);
535 info_ptr
= png_create_info_struct( png_ptr
);
539 if (setjmp(wxinfo
.jmpbuf
))
542 png_read_info( png_ptr
, info_ptr
);
543 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, NULL
, NULL
);
545 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
546 png_set_expand( png_ptr
);
548 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
550 png_set_expand( png_ptr
);
552 png_set_strip_16( png_ptr
);
553 png_set_packing( png_ptr
);
554 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
555 png_set_expand( png_ptr
);
556 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
558 image
->Create((int)width
, (int)height
, (bool) false /* no need to init pixels */);
563 // initialize all line pointers to NULL to ensure that they can be safely
564 // free()d if an error occurs before all of them could be allocated
565 lines
= (unsigned char **)calloc(height
, sizeof(unsigned char *));
569 for (i
= 0; i
< height
; i
++)
571 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
575 png_read_image( png_ptr
, lines
);
576 png_read_end( png_ptr
, info_ptr
);
579 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
581 const size_t ncolors
= info_ptr
->num_palette
;
582 unsigned char* r
= new unsigned char[ncolors
];
583 unsigned char* g
= new unsigned char[ncolors
];
584 unsigned char* b
= new unsigned char[ncolors
];
586 for (size_t j
= 0; j
< ncolors
; j
++)
588 r
[j
] = info_ptr
->palette
[j
].red
;
589 g
[j
] = info_ptr
->palette
[j
].green
;
590 b
[j
] = info_ptr
->palette
[j
].blue
;
593 image
->SetPalette(wxPalette(ncolors
, r
, g
, b
));
598 #endif // wxUSE_PALETTE
600 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
602 // loaded successfully, now init wxImage with this data
603 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
605 for ( i
= 0; i
< height
; i
++ )
614 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
624 for ( unsigned int n
= 0; n
< height
; n
++ )
634 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
638 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
643 // ----------------------------------------------------------------------------
645 // ----------------------------------------------------------------------------
647 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
649 wxPNGInfoStruct wxinfo
;
651 wxinfo
.verbose
= verbose
;
652 wxinfo
.stream
.out
= &stream
;
654 png_structp png_ptr
= png_create_write_struct
656 PNG_LIBPNG_VER_STRING
,
665 wxLogError(_("Couldn't save PNG image."));
670 png_infop info_ptr
= png_create_info_struct(png_ptr
);
671 if (info_ptr
== NULL
)
673 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
676 wxLogError(_("Couldn't save PNG image."));
681 if (setjmp(wxinfo
.jmpbuf
))
683 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
686 wxLogError(_("Couldn't save PNG image."));
691 // NB: please see the comment near wxPNGInfoStruct declaration for
692 // explanation why this line is mandatory
693 png_set_write_fn( png_ptr
, &wxinfo
, wx_PNG_stream_writer
, NULL
);
695 const int iColorType
= image
->HasOption(wxIMAGE_OPTION_PNG_FORMAT
)
696 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT
)
698 const int iBitDepth
= image
->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH
)
699 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH
)
702 bool bHasAlpha
= image
->HasAlpha();
703 bool bHasMask
= image
->HasMask();
704 bool bUseAlpha
= bHasAlpha
|| bHasMask
;
707 if ( iColorType
==wxPNG_TYPE_COLOUR
)
709 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_RGB_ALPHA
710 : PNG_COLOR_TYPE_RGB
;
714 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_GRAY_ALPHA
715 : PNG_COLOR_TYPE_GRAY
;
718 if (image
->HasOption(wxIMAGE_OPTION_PNG_FILTER
))
719 png_set_filter( png_ptr
, PNG_FILTER_TYPE_BASE
, image
->GetOptionInt(wxIMAGE_OPTION_PNG_FILTER
) );
721 if (image
->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL
))
722 png_set_compression_level( png_ptr
, image
->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL
) );
724 if (image
->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL
))
725 png_set_compression_mem_level( png_ptr
, image
->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL
) );
727 if (image
->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY
))
728 png_set_compression_strategy( png_ptr
, image
->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY
) );
730 if (image
->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE
))
731 png_set_compression_buffer_size( png_ptr
, image
->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE
) );
733 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(),
734 iBitDepth
, iPngColorType
,
735 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_BASE
,
736 PNG_FILTER_TYPE_BASE
);
741 if ( iPngColorType
& PNG_COLOR_MASK_COLOR
)
745 sig_bit
.blue
= (png_byte
)iBitDepth
;
750 sig_bit
.gray
= (png_byte
)iBitDepth
;
754 if ( iPngColorType
& PNG_COLOR_MASK_ALPHA
)
756 sig_bit
.alpha
= (png_byte
)iBitDepth
;
760 if ( iBitDepth
== 16 )
763 // save the image resolution if we have it
765 switch ( GetResolutionFromOptions(*image
, &resX
, &resY
) )
767 case wxIMAGE_RESOLUTION_INCHES
:
769 const double INCHES_IN_METER
= 10000.0 / 254;
770 resX
= int(resX
* INCHES_IN_METER
);
771 resY
= int(resY
* INCHES_IN_METER
);
775 case wxIMAGE_RESOLUTION_CM
:
780 case wxIMAGE_RESOLUTION_NONE
:
784 wxFAIL_MSG( _T("unsupported image resolution units") );
788 png_set_pHYs( png_ptr
, info_ptr
, resX
, resY
, PNG_RESOLUTION_METER
);
790 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
791 png_write_info( png_ptr
, info_ptr
);
792 png_set_shift( png_ptr
, &sig_bit
);
793 png_set_packing( png_ptr
);
796 data
= (unsigned char *)malloc( image
->GetWidth() * iElements
);
799 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
804 pAlpha
= (unsigned char *)(bHasAlpha
? image
->GetAlpha() : NULL
);
805 int iHeight
= image
->GetHeight();
806 int iWidth
= image
->GetWidth();
808 unsigned char uchMaskRed
= 0, uchMaskGreen
= 0, uchMaskBlue
= 0;
812 uchMaskRed
= image
->GetMaskRed();
813 uchMaskGreen
= image
->GetMaskGreen();
814 uchMaskBlue
= image
->GetMaskBlue();
817 unsigned char *pColors
= image
->GetData();
819 for (int y
= 0; y
!= iHeight
; ++y
)
821 unsigned char *pData
= data
;
822 for (int x
= 0; x
!= iWidth
; x
++)
824 unsigned char uchRed
= *pColors
++;
825 unsigned char uchGreen
= *pColors
++;
826 unsigned char uchBlue
= *pColors
++;
828 switch ( iColorType
)
831 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
834 case wxPNG_TYPE_COLOUR
:
836 if ( iBitDepth
== 16 )
839 if ( iBitDepth
== 16 )
842 if ( iBitDepth
== 16 )
846 case wxPNG_TYPE_GREY
:
848 // where do these coefficients come from? maybe we
849 // should have image options for them as well?
851 (unsigned) (76.544*(unsigned)uchRed
+
852 150.272*(unsigned)uchGreen
+
853 36.864*(unsigned)uchBlue
);
855 *pData
++ = (unsigned char)((uiColor
>> 8) & 0xFF);
856 if ( iBitDepth
== 16 )
857 *pData
++ = (unsigned char)(uiColor
& 0xFF);
861 case wxPNG_TYPE_GREY_RED
:
863 if ( iBitDepth
== 16 )
870 unsigned char uchAlpha
= 255;
872 uchAlpha
= *pAlpha
++;
876 if ( (uchRed
== uchMaskRed
)
877 && (uchGreen
== uchMaskGreen
)
878 && (uchBlue
== uchMaskBlue
) )
883 if ( iBitDepth
== 16 )
888 png_bytep row_ptr
= data
;
889 png_write_rows( png_ptr
, &row_ptr
, 1 );
893 png_write_end( png_ptr
, info_ptr
);
894 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
900 #pragma warning(default:4611)
903 #endif // wxUSE_STREAMS
905 #endif // wxUSE_LIBPNG