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 static const double INCHES_IN_METER
= 39.3700787;
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // return the kind of transparency needed for this image assuming that it does
73 // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
75 CheckTransparency(unsigned char **lines
,
76 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
79 // init the alpha channel for the image and fill it with 1s up to (x, y)
80 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
82 // find a free colour for the mask in the PNG data array
84 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
85 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
87 // is the pixel with this value of alpha a fully opaque one?
89 bool IsOpaque(unsigned char a
)
94 // is the pixel with this value of alpha a fully transparent one?
96 bool IsTransparent(unsigned char a
)
101 // ============================================================================
102 // wxPNGHandler implementation
103 // ============================================================================
105 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
109 #ifndef PNGLINKAGEMODE
111 // we need an explicit cdecl for Watcom, at least according to
113 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
115 // more testing is needed for this however, please remove this comment
116 // if you can confirm that my fix works with Watcom 11
117 #define PNGLINKAGEMODE cdecl
119 #define PNGLINKAGEMODE LINKAGEMODE
124 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
125 // First, let me describe what's the problem: libpng uses jmp_buf in
126 // its png_struct structure. Unfortunately, this structure is
127 // compiler-specific and may vary in size, so if you use libpng compiled
128 // as DLL with another compiler than the main executable, it may not work
129 // (this is for example the case with wxMGL port and SciTech MGL library
130 // that provides custom runtime-loadable libpng implementation with jmpbuf
131 // disabled altogether). Luckily, it is still possible to use setjmp() &
132 // longjmp() as long as the structure is not part of png_struct.
134 // Sadly, there's no clean way to attach user-defined data to png_struct.
135 // There is only one customizable place, png_struct.io_ptr, which is meant
136 // only for I/O routines and is set with png_set_read_fn or
137 // png_set_write_fn. The hacky part is that we use io_ptr to store
138 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
140 struct wxPNGInfoStruct
152 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
161 void PNGLINKAGEMODE
wx_PNG_stream_reader( png_structp png_ptr
, png_bytep data
,
164 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
167 void PNGLINKAGEMODE
wx_PNG_stream_writer( png_structp png_ptr
, png_bytep data
,
170 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
174 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
176 wxPNGInfoStruct
*info
= png_ptr
? WX_PNG_INFO(png_ptr
) : NULL
;
177 if ( !info
|| info
->verbose
)
178 wxLogWarning( wxString::FromAscii(message
) );
182 // so that the libpng doesn't send anything on stderr
184 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
186 wx_png_warning(NULL
, message
);
188 // we're not using libpng built-in jump buffer (see comment before
189 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
191 longjmp(WX_PNG_INFO(png_ptr
)->jmpbuf
, 1);
196 // ----------------------------------------------------------------------------
197 // LoadFile() helpers
198 // ----------------------------------------------------------------------------
200 // determine the kind of transparency we need for this image: if the only alpha
201 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
202 // create a mask for it, we should be ok with a simple mask but otherwise we
203 // need a full blown alpha channel in wxImage
206 // lines raw PNG data
207 // x, y starting position
208 // w, h size of the image
209 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
210 // (NB: alpha always follows the colour bytes)
212 CheckTransparency(unsigned char **lines
,
213 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
216 // suppose that a mask will suffice and check all the remaining alpha
217 // values to see if it does
220 // each pixel is numColBytes+1 bytes, offset into the current line by
221 // the current x position
222 unsigned const char *ptr
= lines
[y
] + (x
* (numColBytes
+ 1));
224 for ( png_uint_32 x2
= x
; x2
< w
; x2
++ )
226 // skip the grey or colour byte(s)
229 unsigned char a2
= *ptr
++;
231 if ( !IsTransparent(a2
) && !IsOpaque(a2
) )
233 // not fully opaque nor fully transparent, hence need alpha
234 return Transparency_Alpha
;
238 // during the next loop iteration check all the pixels in the row
242 // mask will be enough
243 return Transparency_Mask
;
246 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
248 // create alpha channel
251 unsigned char *alpha
= image
->GetAlpha();
253 // set alpha for the pixels we had so far
254 png_uint_32 end
= y
* image
->GetWidth() + x
;
255 for ( png_uint_32 i
= 0; i
< end
; i
++ )
257 // all the previous pixels were opaque
265 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
266 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
268 // choosing the colour for the mask is more
269 // difficult: we need to iterate over the entire
270 // image for this in order to choose an unused
271 // colour (this is not very efficient but what else
274 unsigned nentries
= 0;
275 unsigned char r2
, g2
, b2
;
276 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
278 const unsigned char *p
= lines
[y2
];
279 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
284 ++p
; // jump over alpha
286 wxImageHistogramEntry
&
287 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
289 if ( entry
.value
++ == 0 )
290 entry
.index
= nentries
++;
294 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
296 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
298 // use a fixed mask colour and we'll fudge
299 // the real pixels with this colour (see
307 // ----------------------------------------------------------------------------
309 // ----------------------------------------------------------------------------
311 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
313 unsigned char hdr
[4];
315 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
318 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
321 // convert data from RGB to wxImage format
323 void CopyDataFromPNG(wxImage
*image
,
324 unsigned char **lines
,
329 Transparency transparency
= Transparency_None
;
331 // only non NULL if transparency == Transparency_Alpha
332 unsigned char *alpha
= NULL
;
334 // RGB of the mask colour if transparency == Transparency_Mask
335 // (but init them anyhow to avoid compiler warnings)
336 unsigned char rMask
= 0,
340 unsigned char *ptrDst
= image
->GetData();
341 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
343 // grey image: GAGAGA... where G == grey component and A == alpha
344 for ( png_uint_32 y
= 0; y
< height
; y
++ )
346 const unsigned char *ptrSrc
= lines
[y
];
347 for ( png_uint_32 x
= 0; x
< width
; x
++ )
349 unsigned char g
= *ptrSrc
++;
350 unsigned char a
= *ptrSrc
++;
352 // the first time we encounter a transparent pixel we must
353 // decide about what to do about them
354 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
356 // we'll need at least the mask for this image and
357 // maybe even full alpha channel info: the former is
358 // only enough if we have alpha values of 0 and 0xff
359 // only, otherwisewe need the latter
360 transparency
= CheckTransparency
368 if ( transparency
== Transparency_Mask
)
370 // let's choose this colour for the mask: this is
371 // not a problem here as all the other pixels are
372 // grey, i.e. R == G == B which is not the case for
373 // this one so no confusion is possible
378 else // transparency == Transparency_Alpha
380 alpha
= InitAlpha(image
, x
, y
);
384 switch ( transparency
)
386 case Transparency_Mask
:
387 if ( IsTransparent(a
) )
394 // else: !transparent
396 // must be opaque then as otherwise we shouldn't be
397 // using the mask at all
398 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
402 case Transparency_Alpha
:
407 case Transparency_None
:
416 else // colour image: RGBRGB...
418 for ( png_uint_32 y
= 0; y
< height
; y
++ )
420 const unsigned char *ptrSrc
= lines
[y
];
421 for ( png_uint_32 x
= 0; x
< width
; x
++ )
423 unsigned char r
= *ptrSrc
++;
424 unsigned char g
= *ptrSrc
++;
425 unsigned char b
= *ptrSrc
++;
426 unsigned char a
= *ptrSrc
++;
428 // the logic here is the same as for the grey case except
430 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
432 transparency
= CheckTransparency
440 if ( transparency
== Transparency_Mask
)
442 FindMaskColour(lines
, width
, height
,
443 rMask
, gMask
, bMask
);
445 else // transparency == Transparency_Alpha
447 alpha
= InitAlpha(image
, x
, y
);
452 switch ( transparency
)
454 case Transparency_Mask
:
455 if ( IsTransparent(a
) )
464 // must be opaque then as otherwise we shouldn't be
465 // using the mask at all
466 wxASSERT_MSG( IsOpaque(a
), _T("logic error") );
468 // if we couldn't find a unique colour for the
469 // mask, we can have real pixels with the same
470 // value as the mask and it's better to slightly
471 // change their colour than to make them
473 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
481 case Transparency_Alpha
:
486 case Transparency_None
:
496 if ( transparency
== Transparency_Mask
)
498 image
->SetMaskColour(rMask
, gMask
, bMask
);
502 // temporarily disable the warning C4611 (interaction between '_setjmp' and
503 // C++ object destruction is non-portable) - I don't see any dtors here
505 #pragma warning(disable:4611)
509 wxPNGHandler::LoadFile(wxImage
*image
,
510 wxInputStream
& stream
,
514 // VZ: as this function uses setjmp() the only fool-proof error handling
515 // method is to use goto (setjmp is not really C++ dtors friendly...)
517 unsigned char **lines
= NULL
;
518 png_infop info_ptr
= (png_infop
) NULL
;
519 wxPNGInfoStruct wxinfo
;
521 png_uint_32 i
, width
, height
= 0;
522 int bit_depth
, color_type
, interlace_type
;
524 wxinfo
.verbose
= verbose
;
525 wxinfo
.stream
.in
= &stream
;
529 png_structp png_ptr
= png_create_read_struct
531 PNG_LIBPNG_VER_STRING
,
539 // NB: please see the comment near wxPNGInfoStruct declaration for
540 // explanation why this line is mandatory
541 png_set_read_fn( png_ptr
, &wxinfo
, wx_PNG_stream_reader
);
543 info_ptr
= png_create_info_struct( png_ptr
);
547 if (setjmp(wxinfo
.jmpbuf
))
550 png_read_info( png_ptr
, info_ptr
);
551 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
553 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
554 png_set_expand( png_ptr
);
556 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
558 png_set_expand( png_ptr
);
560 png_set_strip_16( png_ptr
);
561 png_set_packing( png_ptr
);
562 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
563 png_set_expand( png_ptr
);
564 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
566 image
->Create((int)width
, (int)height
, (bool) false /* no need to init pixels */);
571 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
575 for (i
= 0; i
< height
; i
++)
577 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
579 for ( unsigned int n
= 0; n
< i
; n
++ )
585 png_read_image( png_ptr
, lines
);
586 png_read_end( png_ptr
, info_ptr
);
589 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
591 const size_t ncolors
= info_ptr
->num_palette
;
592 unsigned char* r
= new unsigned char[ncolors
];
593 unsigned char* g
= new unsigned char[ncolors
];
594 unsigned char* b
= new unsigned char[ncolors
];
596 for (size_t j
= 0; j
< ncolors
; j
++)
598 r
[j
] = info_ptr
->palette
[j
].red
;
599 g
[j
] = info_ptr
->palette
[j
].green
;
600 b
[j
] = info_ptr
->palette
[j
].blue
;
603 image
->SetPalette(wxPalette(ncolors
, r
, g
, b
));
608 #endif // wxUSE_PALETTE
610 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
612 // loaded successfully, now init wxImage with this data
613 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
615 for ( i
= 0; i
< height
; i
++ )
623 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
632 for ( unsigned int n
= 0; n
< height
; n
++ )
642 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
646 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
651 // ----------------------------------------------------------------------------
653 // ----------------------------------------------------------------------------
655 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
657 wxPNGInfoStruct wxinfo
;
659 wxinfo
.verbose
= verbose
;
660 wxinfo
.stream
.out
= &stream
;
662 png_structp png_ptr
= png_create_write_struct
664 PNG_LIBPNG_VER_STRING
,
672 wxLogError(_("Couldn't save PNG image."));
676 png_infop info_ptr
= png_create_info_struct(png_ptr
);
677 if (info_ptr
== NULL
)
679 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
681 wxLogError(_("Couldn't save PNG image."));
685 if (setjmp(wxinfo
.jmpbuf
))
687 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
689 wxLogError(_("Couldn't save PNG image."));
693 // NB: please see the comment near wxPNGInfoStruct declaration for
694 // explanation why this line is mandatory
695 png_set_write_fn( png_ptr
, &wxinfo
, wx_PNG_stream_writer
, NULL
);
697 const int iColorType
= image
->HasOption(wxIMAGE_OPTION_PNG_FORMAT
)
698 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT
)
700 const int iBitDepth
= image
->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH
)
701 ? image
->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH
)
704 wxASSERT_MSG( iBitDepth
== 8 || iBitDepth
== 16,
705 _T("PNG bit depth must be 8 or 16") );
707 bool bHasAlpha
= image
->HasAlpha();
708 bool bHasMask
= image
->HasMask();
709 bool bUseAlpha
= bHasAlpha
|| bHasMask
;
712 if ( iColorType
==wxPNG_TYPE_COLOUR
)
714 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_RGB_ALPHA
715 : PNG_COLOR_TYPE_RGB
;
719 iPngColorType
= bUseAlpha
? PNG_COLOR_TYPE_GRAY_ALPHA
720 : PNG_COLOR_TYPE_GRAY
;
723 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(),
724 iBitDepth
, iPngColorType
,
725 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_BASE
,
726 PNG_FILTER_TYPE_BASE
);
731 if ( iPngColorType
& PNG_COLOR_MASK_COLOR
)
735 sig_bit
.blue
= (png_byte
)iBitDepth
;
740 sig_bit
.gray
= (png_byte
)iBitDepth
;
744 if ( iPngColorType
& PNG_COLOR_MASK_ALPHA
)
746 sig_bit
.alpha
= (png_byte
)iBitDepth
;
750 if ( iBitDepth
== 16 )
753 // save the image resolution if we have it
755 switch ( GetResolutionFromOptions(*image
, &resX
, &resY
) )
757 case wxIMAGE_RESOLUTION_INCHES
:
758 resX
*= INCHES_IN_METER
;
759 resY
*= INCHES_IN_METER
;
762 case wxIMAGE_RESOLUTION_CM
:
767 case wxIMAGE_RESOLUTION_NONE
:
771 wxFAIL_MSG( _T("unsupported image resolution units") );
775 png_set_pHYs( png_ptr
, info_ptr
, resX
, resY
, PNG_RESOLUTION_METER
);
777 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
778 png_write_info( png_ptr
, info_ptr
);
779 png_set_shift( png_ptr
, &sig_bit
);
780 png_set_packing( png_ptr
);
783 data
= (unsigned char *)malloc( image
->GetWidth() * iElements
);
786 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
791 pAlpha
= (unsigned char *)(bHasAlpha
? image
->GetAlpha() : NULL
);
792 int iHeight
= image
->GetHeight();
793 int iWidth
= image
->GetWidth();
795 unsigned char uchMaskRed
= 0, uchMaskGreen
= 0, uchMaskBlue
= 0;
799 uchMaskRed
= image
->GetMaskRed();
800 uchMaskGreen
= image
->GetMaskGreen();
801 uchMaskBlue
= image
->GetMaskBlue();
804 unsigned char *pColors
= image
->GetData();
806 for (int y
= 0; y
!= iHeight
; ++y
)
808 unsigned char *pData
= data
;
809 for (int x
= 0; x
!= iWidth
; x
++)
811 unsigned char uchRed
= *pColors
++;
812 unsigned char uchGreen
= *pColors
++;
813 unsigned char uchBlue
= *pColors
++;
815 switch ( iColorType
)
818 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
821 case wxPNG_TYPE_COLOUR
:
823 if ( iBitDepth
== 16 )
826 if ( iBitDepth
== 16 )
829 if ( iBitDepth
== 16 )
833 case wxPNG_TYPE_GREY
:
835 // where do these coefficients come from? maybe we
836 // should have image options for them as well?
838 (unsigned) (76.544*(unsigned)uchRed
+
839 150.272*(unsigned)uchGreen
+
840 36.864*(unsigned)uchBlue
);
842 *pData
++ = (unsigned char)((uiColor
>> 8) & 0xFF);
843 if ( iBitDepth
== 16 )
844 *pData
++ = (unsigned char)(uiColor
& 0xFF);
848 case wxPNG_TYPE_GREY_RED
:
850 if ( iBitDepth
== 16 )
857 unsigned char uchAlpha
= 255;
859 uchAlpha
= *pAlpha
++;
863 if ( (uchRed
== uchMaskRed
)
864 && (uchGreen
== uchMaskGreen
)
865 && (uchBlue
== uchMaskBlue
) )
870 if ( iBitDepth
== 16 )
875 png_bytep row_ptr
= data
;
876 png_write_rows( png_ptr
, &row_ptr
, 1 );
880 png_write_end( png_ptr
, info_ptr
);
881 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
887 #pragma warning(default:4611)
890 #endif // wxUSE_STREAMS
892 #endif // wxUSE_LIBPNG