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"
40 #include "wx/palette.h"
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
55 // image can not have any transparent pixels at all, have only 100% opaque
56 // and/or 100% transparent pixels in which case a simple mask is enough to
57 // store this information in wxImage or have a real alpha channel in which case
58 // we need to have it in wxImage as well
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
70 // return the kind of transparency needed for this image assuming that it does
71 // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
73 CheckTransparency(unsigned char **lines
,
74 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
77 // init the alpha channel for the image and fill it with 1s up to (x, y)
78 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
80 // find a free colour for the mask in the PNG data array
82 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
83 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
85 // is the pixel with this value of alpha a fully opaque one?
87 bool IsOpaque(unsigned char a
)
92 // is the pixel with this value of alpha a fully transparent one?
94 bool IsTransparent(unsigned char a
)
99 // ============================================================================
100 // wxPNGHandler implementation
101 // ============================================================================
103 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
107 #ifndef PNGLINKAGEMODE
109 // we need an explicit cdecl for Watcom, at least according to
111 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
113 // more testing is needed for this however, please remove this comment
114 // if you can confirm that my fix works with Watcom 11
115 #define PNGLINKAGEMODE cdecl
117 #define PNGLINKAGEMODE LINKAGEMODE
122 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
123 // First, let me describe what's the problem: libpng uses jmp_buf in
124 // its png_struct structure. Unfortunately, this structure is
125 // compiler-specific and may vary in size, so if you use libpng compiled
126 // as DLL with another compiler than the main executable, it may not work
127 // (this is for example the case with wxMGL port and SciTech MGL library
128 // that provides custom runtime-loadable libpng implementation with jmpbuf
129 // disabled altogether). Luckily, it is still possible to use setjmp() &
130 // longjmp() as long as the structure is not part of png_struct.
132 // Sadly, there's no clean way to attach user-defined data to png_struct.
133 // There is only one customizable place, png_struct.io_ptr, which is meant
134 // only for I/O routines and is set with png_set_read_fn or
135 // png_set_write_fn. The hacky part is that we use io_ptr to store
136 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
138 struct wxPNGInfoStruct
150 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
152 // ----------------------------------------------------------------------------
154 // ----------------------------------------------------------------------------
159 void PNGLINKAGEMODE
wx_PNG_stream_reader( png_structp png_ptr
, png_bytep data
,
162 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
165 void PNGLINKAGEMODE
wx_PNG_stream_writer( png_structp png_ptr
, png_bytep data
,
168 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
172 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
174 wxPNGInfoStruct
*info
= png_ptr
? WX_PNG_INFO(png_ptr
) : NULL
;
175 if ( !info
|| info
->verbose
)
176 wxLogWarning( wxString::FromAscii(message
) );
180 // so that the libpng doesn't send anything on stderr
182 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
184 wx_png_warning(NULL
, message
);
186 // we're not using libpng built-in jump buffer (see comment before
187 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
189 longjmp(WX_PNG_INFO(png_ptr
)->jmpbuf
, 1);
194 // ----------------------------------------------------------------------------
195 // LoadFile() helpers
196 // ----------------------------------------------------------------------------
198 // determine the kind of transparency we need for this image: if the only alpha
199 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
200 // create a mask for it, we should be ok with a simple mask but otherwise we
201 // need a full blown alpha channel in wxImage
204 // lines raw PNG data
205 // x, y starting position
206 // w, h size of the image
207 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
208 // (NB: alpha always follows the colour bytes)
210 CheckTransparency(unsigned char **lines
,
211 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
214 // suppose that a mask will suffice and check all the remaining alpha
215 // values to see if it does
218 // each pixel is numColBytes+1 bytes, offset into the current line by
219 // the current x position
220 unsigned const char *ptr
= lines
[y
] + (x
* (numColBytes
+ 1));
222 for ( png_uint_32 x2
= x
; x2
< w
; x2
++ )
224 // skip the grey or colour byte(s)
227 unsigned char a2
= *ptr
++;
229 if ( !IsTransparent(a2
) && !IsOpaque(a2
) )
231 // not fully opaque nor fully transparent, hence need alpha
232 return Transparency_Alpha
;
236 // during the next loop iteration check all the pixels in the row
240 // mask will be enough
241 return Transparency_Mask
;
244 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
246 // create alpha channel
249 unsigned char *alpha
= image
->GetAlpha();
251 // set alpha for the pixels we had so far
252 png_uint_32 end
= y
* image
->GetWidth() + x
;
253 for ( png_uint_32 i
= 0; i
< end
; i
++ )
255 // all the previous pixels were opaque
263 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
264 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
266 // choosing the colour for the mask is more
267 // difficult: we need to iterate over the entire
268 // image for this in order to choose an unused
269 // colour (this is not very efficient but what else
272 unsigned nentries
= 0;
273 unsigned char r2
, g2
, b2
;
274 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
276 const unsigned char *p
= lines
[y2
];
277 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
282 ++p
; // jump over alpha
284 wxImageHistogramEntry
&
285 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
287 if ( entry
.value
++ == 0 )
288 entry
.index
= nentries
++;
292 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
294 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
296 // use a fixed mask colour and we'll fudge
297 // the real pixels with this colour (see
305 // ----------------------------------------------------------------------------
307 // ----------------------------------------------------------------------------
309 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
311 unsigned char hdr
[4];
313 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
316 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
319 // convert data from RGB to wxImage format
321 void CopyDataFromPNG(wxImage
*image
,
322 unsigned char **lines
,
327 Transparency transparency
= Transparency_None
;
329 // only non NULL if transparency == Transparency_Alpha
330 unsigned char *alpha
= NULL
;
332 // RGB of the mask colour if transparency == Transparency_Mask
333 // (but init them anyhow to avoid compiler warnings)
334 unsigned char rMask
= 0,
338 unsigned char *ptrDst
= image
->GetData();
339 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
341 // grey image: GAGAGA... where G == grey component and A == alpha
342 for ( png_uint_32 y
= 0; y
< height
; y
++ )
344 const unsigned char *ptrSrc
= lines
[y
];
345 for ( png_uint_32 x
= 0; x
< width
; x
++ )
347 unsigned char g
= *ptrSrc
++;
348 unsigned char a
= *ptrSrc
++;
350 // the first time we encounter a transparent pixel we must
351 // decide about what to do about them
352 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
354 // we'll need at least the mask for this image and
355 // maybe even full alpha channel info: the former is
356 // only enough if we have alpha values of 0 and 0xff
357 // only, otherwisewe need the latter
358 transparency
= CheckTransparency
366 if ( transparency
== Transparency_Mask
)
368 // let's choose this colour for the mask: this is
369 // not a problem here as all the other pixels are
370 // grey, i.e. R == G == B which is not the case for
371 // this one so no confusion is possible
376 else // transparency == Transparency_Alpha
378 alpha
= InitAlpha(image
, x
, y
);
382 switch ( transparency
)
384 case Transparency_Mask
:
385 if ( IsTransparent(a
) )
392 // else: !transparent
394 // must be opaque then as otherwise we shouldn't be
395 // using the mask at all
396 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
400 case Transparency_Alpha
:
405 case Transparency_None
:
414 else // colour image: RGBRGB...
416 for ( png_uint_32 y
= 0; y
< height
; y
++ )
418 const unsigned char *ptrSrc
= lines
[y
];
419 for ( png_uint_32 x
= 0; x
< width
; x
++ )
421 unsigned char r
= *ptrSrc
++;
422 unsigned char g
= *ptrSrc
++;
423 unsigned char b
= *ptrSrc
++;
424 unsigned char a
= *ptrSrc
++;
426 // the logic here is the same as for the grey case except
428 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
430 transparency
= CheckTransparency
438 if ( transparency
== Transparency_Mask
)
440 FindMaskColour(lines
, width
, height
,
441 rMask
, gMask
, bMask
);
443 else // transparency == Transparency_Alpha
445 alpha
= InitAlpha(image
, x
, y
);
450 switch ( transparency
)
452 case Transparency_Mask
:
453 if ( IsTransparent(a
) )
462 // must be opaque then as otherwise we shouldn't be
463 // using the mask at all
464 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
466 // if we couldn't find a unique colour for the
467 // mask, we can have real pixels with the same
468 // value as the mask and it's better to slightly
469 // change their colour than to make them
471 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
479 case Transparency_Alpha
:
484 case Transparency_None
:
494 if ( transparency
== Transparency_Mask
)
496 image
->SetMaskColour(rMask
, gMask
, bMask
);
500 // temporarily disable the warning C4611 (interaction between '_setjmp' and
501 // C++ object destruction is non-portable) - I don't see any dtors here
503 #pragma warning(disable:4611)
507 wxPNGHandler::LoadFile(wxImage
*image
,
508 wxInputStream
& stream
,
512 // VZ: as this function uses setjmp() the only fool-proof error handling
513 // method is to use goto (setjmp is not really C++ dtors friendly...)
515 unsigned char **lines
= NULL
;
516 png_infop info_ptr
= (png_infop
) NULL
;
517 wxPNGInfoStruct wxinfo
;
519 png_uint_32 i
, width
, height
= 0;
520 int bit_depth
, color_type
, interlace_type
;
522 wxinfo
.verbose
= verbose
;
523 wxinfo
.stream
.in
= &stream
;
527 png_structp png_ptr
= png_create_read_struct
529 PNG_LIBPNG_VER_STRING
,
537 // NB: please see the comment near wxPNGInfoStruct declaration for
538 // explanation why this line is mandatory
539 png_set_read_fn( png_ptr
, &wxinfo
, wx_PNG_stream_reader
);
541 info_ptr
= png_create_info_struct( png_ptr
);
545 if (setjmp(wxinfo
.jmpbuf
))
548 png_read_info( png_ptr
, info_ptr
);
549 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
551 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
552 png_set_expand( png_ptr
);
554 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
556 png_set_expand( png_ptr
);
558 png_set_strip_16( png_ptr
);
559 png_set_packing( png_ptr
);
560 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
561 png_set_expand( png_ptr
);
562 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
564 image
->Create((int)width
, (int)height
, (bool) false /* no need to init pixels */);
569 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
573 for (i
= 0; i
< height
; i
++)
575 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
577 for ( unsigned int n
= 0; n
< i
; n
++ )
583 png_read_image( png_ptr
, lines
);
584 png_read_end( png_ptr
, info_ptr
);
587 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
589 const size_t ncolors
= info_ptr
->num_palette
;
590 unsigned char* r
= new unsigned char[ncolors
];
591 unsigned char* g
= new unsigned char[ncolors
];
592 unsigned char* b
= new unsigned char[ncolors
];
594 for (size_t j
= 0; j
< ncolors
; j
++)
596 r
[j
] = info_ptr
->palette
[j
].red
;
597 g
[j
] = info_ptr
->palette
[j
].green
;
598 b
[j
] = info_ptr
->palette
[j
].blue
;
601 image
->SetPalette(wxPalette(ncolors
, r
, g
, b
));
606 #endif // wxUSE_PALETTE
608 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
610 // loaded successfully, now init wxImage with this data
611 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
613 for ( i
= 0; i
< height
; i
++ )
621 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
630 for ( unsigned int n
= 0; n
< height
; n
++ )
640 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
644 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
649 // ----------------------------------------------------------------------------
651 // ----------------------------------------------------------------------------
653 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
655 wxPNGInfoStruct wxinfo
;
657 wxinfo
.verbose
= verbose
;
658 wxinfo
.stream
.out
= &stream
;
660 png_structp png_ptr
= png_create_write_struct
662 PNG_LIBPNG_VER_STRING
,
670 wxLogError(_("Couldn't save PNG image."));
674 png_infop info_ptr
= png_create_info_struct(png_ptr
);
675 if (info_ptr
== NULL
)
677 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
679 wxLogError(_("Couldn't save PNG image."));
683 if (setjmp(wxinfo
.jmpbuf
))
685 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
687 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 wxASSERT_MSG( iBitDepth
== 8 || iBitDepth
== 16,
703 _T("PNG bit depth must be 8 or 16") );
705 bool bHasAlpha
= image
->HasAlpha();
706 bool bHasMask
= image
->HasMask();
707 bool bUseAlpha
= bHasAlpha
|| bHasMask
;
710 if ( iColorType
==wxPNG_TYPE_COLOUR
)
712 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_RGB_ALPHA
713 : PNG_COLOR_TYPE_RGB
;
717 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_GRAY_ALPHA
718 : PNG_COLOR_TYPE_GRAY
;
721 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(),
722 iBitDepth
, iPngColorType
,
723 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_BASE
,
724 PNG_FILTER_TYPE_BASE
);
729 if ( iPngColorType
& PNG_COLOR_MASK_COLOR
)
733 sig_bit
.blue
= (png_byte
)iBitDepth
;
738 sig_bit
.gray
= (png_byte
)iBitDepth
;
742 if ( iPngColorType
& PNG_COLOR_MASK_ALPHA
)
744 sig_bit
.alpha
= (png_byte
)iBitDepth
;
748 if ( iBitDepth
== 16 )
751 // save the image resolution if we have it
753 switch ( GetResolutionFromOptions(*image
, &resX
, &resY
) )
755 case wxIMAGE_RESOLUTION_INCHES
:
757 const double INCHES_IN_METER
= 10000.0 / 254;
758 resX
= int(resX
* INCHES_IN_METER
);
759 resY
= int(resY
* INCHES_IN_METER
);
763 case wxIMAGE_RESOLUTION_CM
:
768 case wxIMAGE_RESOLUTION_NONE
:
772 wxFAIL_MSG( _T("unsupported image resolution units") );
776 png_set_pHYs( png_ptr
, info_ptr
, resX
, resY
, PNG_RESOLUTION_METER
);
778 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
779 png_write_info( png_ptr
, info_ptr
);
780 png_set_shift( png_ptr
, &sig_bit
);
781 png_set_packing( png_ptr
);
784 data
= (unsigned char *)malloc( image
->GetWidth() * iElements
);
787 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
792 pAlpha
= (unsigned char *)(bHasAlpha
? image
->GetAlpha() : NULL
);
793 int iHeight
= image
->GetHeight();
794 int iWidth
= image
->GetWidth();
796 unsigned char uchMaskRed
= 0, uchMaskGreen
= 0, uchMaskBlue
= 0;
800 uchMaskRed
= image
->GetMaskRed();
801 uchMaskGreen
= image
->GetMaskGreen();
802 uchMaskBlue
= image
->GetMaskBlue();
805 unsigned char *pColors
= image
->GetData();
807 for (int y
= 0; y
!= iHeight
; ++y
)
809 unsigned char *pData
= data
;
810 for (int x
= 0; x
!= iWidth
; x
++)
812 unsigned char uchRed
= *pColors
++;
813 unsigned char uchGreen
= *pColors
++;
814 unsigned char uchBlue
= *pColors
++;
816 switch ( iColorType
)
819 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
822 case wxPNG_TYPE_COLOUR
:
824 if ( iBitDepth
== 16 )
827 if ( iBitDepth
== 16 )
830 if ( iBitDepth
== 16 )
834 case wxPNG_TYPE_GREY
:
836 // where do these coefficients come from? maybe we
837 // should have image options for them as well?
839 (unsigned) (76.544*(unsigned)uchRed
+
840 150.272*(unsigned)uchGreen
+
841 36.864*(unsigned)uchBlue
);
843 *pData
++ = (unsigned char)((uiColor
>> 8) & 0xFF);
844 if ( iBitDepth
== 16 )
845 *pData
++ = (unsigned char)(uiColor
& 0xFF);
849 case wxPNG_TYPE_GREY_RED
:
851 if ( iBitDepth
== 16 )
858 unsigned char uchAlpha
= 255;
860 uchAlpha
= *pAlpha
++;
864 if ( (uchRed
== uchMaskRed
)
865 && (uchGreen
== uchMaskGreen
)
866 && (uchBlue
== uchMaskBlue
) )
871 if ( iBitDepth
== 16 )
876 png_bytep row_ptr
= data
;
877 png_write_rows( png_ptr
, &row_ptr
, 1 );
881 png_write_end( png_ptr
, info_ptr
);
882 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
888 #pragma warning(default:4611)
891 #endif // wxUSE_STREAMS
893 #endif // wxUSE_LIBPNG