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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
15 #pragma implementation "imagpng.h"
18 // ----------------------------------------------------------------------------
20 // ----------------------------------------------------------------------------
22 // For compilers that support precompilation, includes "wx.h".
23 #include "wx/wxprec.h"
33 #if wxUSE_IMAGE && wxUSE_LIBPNG
35 #include "wx/imagpng.h"
36 #include "wx/bitmap.h"
41 #include "wx/filefn.h"
42 #include "wx/wfstream.h"
44 #include "wx/module.h"
55 // ----------------------------------------------------------------------------
57 // ----------------------------------------------------------------------------
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
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
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
77 CheckTransparency(unsigned char **lines
,
78 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
81 // init the alpha channel for the image and fill it with 1s up to (x, y)
82 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
84 // find a free colour for the mask in the PNG data array
86 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
87 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
89 // is the pixel with this value of alpha a fully opaque one?
91 bool IsOpaque(unsigned char a
)
96 // is the pixel with this value of alpha a fully transparent one?
98 bool IsTransparent(unsigned char a
)
103 // ============================================================================
104 // wxPNGHandler implementation
105 // ============================================================================
107 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
111 #ifndef PNGLINKAGEMODE
113 // we need an explicit cdecl for Watcom, at least according to
115 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
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
121 #define PNGLINKAGEMODE LINKAGEMODE
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.
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.
142 struct wxPNGInfoStruct
154 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
156 // ----------------------------------------------------------------------------
158 // ----------------------------------------------------------------------------
163 void PNGLINKAGEMODE
wx_PNG_stream_reader( png_structp png_ptr
, png_bytep data
,
166 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
169 void PNGLINKAGEMODE
wx_PNG_stream_writer( png_structp png_ptr
, png_bytep data
,
172 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
176 // so that the libpng doesn't send anything on stderr
178 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
180 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
182 wxLogError( wxString::FromAscii(message
) );
184 #ifdef USE_FAR_KEYWORD
187 png_memcpy(jmpbuf
,info
->jmpbuf
,sizeof(jmp_buf));
191 longjmp(info
->jmpbuf
, 1);
196 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
198 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
200 wxLogWarning( wxString::FromAscii(message
) );
205 // ----------------------------------------------------------------------------
206 // LoadFile() helpers
207 // ----------------------------------------------------------------------------
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
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)
221 CheckTransparency(unsigned char **lines
,
222 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
225 // suppose that a mask will suffice and check all the remaining alpha
226 // values to see if it does
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));
233 for ( png_uint_32 x2
= x
; x2
< w
; x2
++ )
235 // skip the grey or colour byte(s)
238 unsigned char a2
= *ptr
++;
240 if ( !IsTransparent(a2
) && !IsOpaque(a2
) )
242 // not fully opaque nor fully transparent, hence need alpha
243 return Transparency_Alpha
;
247 // during the next loop iteration check all the pixels in the row
251 // mask will be enough
252 return Transparency_Mask
;
255 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
257 // create alpha channel
260 unsigned char *alpha
= image
->GetAlpha();
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
++ )
266 // all the previous pixels were opaque
274 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
275 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
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
283 unsigned nentries
= 0;
284 unsigned char r2
, g2
, b2
;
285 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
287 const unsigned char *p
= lines
[y2
];
288 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
294 wxImageHistogramEntry
&
295 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
297 if ( entry
.value
++ == 0 )
298 entry
.index
= nentries
++;
302 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
304 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
306 // use a fixed mask colour and we'll fudge
307 // the real pixels with this colour (see
315 // ----------------------------------------------------------------------------
317 // ----------------------------------------------------------------------------
319 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
321 unsigned char hdr
[4];
323 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
326 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
329 // convert data from RGB to wxImage format
331 void CopyDataFromPNG(wxImage
*image
,
332 unsigned char **lines
,
337 Transparency transparency
= Transparency_None
;
339 // only non NULL if transparency == Transparency_Alpha
340 unsigned char *alpha
= NULL
;
342 // RGB of the mask colour if transparency == Transparency_Mask
343 // (but init them anyhow to avoid compiler warnings)
344 unsigned char rMask
= 0,
348 unsigned char *ptrDst
= image
->GetData();
349 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
351 // grey image: GAGAGA... where G == grey component and A == alpha
352 for ( png_uint_32 y
= 0; y
< height
; y
++ )
354 const unsigned char *ptrSrc
= lines
[y
];
355 for ( png_uint_32 x
= 0; x
< width
; x
++ )
357 unsigned char g
= *ptrSrc
++;
358 unsigned char a
= *ptrSrc
++;
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
)
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
376 if ( transparency
== Transparency_Mask
)
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
386 else // transparency == Transparency_Alpha
388 alpha
= InitAlpha(image
, x
, y
);
392 switch ( transparency
)
394 case Transparency_Mask
:
395 if ( IsTransparent(a
) )
402 // else: !transparent
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") );
410 case Transparency_Alpha
:
415 case Transparency_None
:
424 else // colour image: RGBRGB...
426 for ( png_uint_32 y
= 0; y
< height
; y
++ )
428 const unsigned char *ptrSrc
= lines
[y
];
429 for ( png_uint_32 x
= 0; x
< width
; x
++ )
431 unsigned char r
= *ptrSrc
++;
432 unsigned char g
= *ptrSrc
++;
433 unsigned char b
= *ptrSrc
++;
434 unsigned char a
= *ptrSrc
++;
436 // the logic here is the same as for the grey case except
438 if ( !IsOpaque(a
) && transparency
== Transparency_None
)
440 transparency
= CheckTransparency
448 if ( transparency
== Transparency_Mask
)
450 FindMaskColour(lines
, width
, height
,
451 rMask
, gMask
, bMask
);
453 else // transparency == Transparency_Alpha
455 alpha
= InitAlpha(image
, x
, y
);
460 switch ( transparency
)
462 case Transparency_Mask
:
463 if ( IsTransparent(a
) )
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") );
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
481 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
489 case Transparency_Alpha
:
494 case Transparency_None
:
504 if ( transparency
== Transparency_Mask
)
506 image
->SetMaskColour(rMask
, gMask
, bMask
);
510 // temporarily disable the warning C4611 (interaction between '_setjmp' and
511 // C++ object destruction is non-portable) - I don't see any dtors here
513 #pragma warning(disable:4611)
517 wxPNGHandler::LoadFile(wxImage
*image
,
518 wxInputStream
& stream
,
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...)
525 unsigned char **lines
= NULL
;
526 png_infop info_ptr
= (png_infop
) NULL
;
527 wxPNGInfoStruct wxinfo
;
529 wxinfo
.verbose
= verbose
;
530 wxinfo
.stream
.in
= &stream
;
534 png_structp png_ptr
= png_create_read_struct( PNG_LIBPNG_VER_STRING
,
536 (png_error_ptr
) NULL
,
537 (png_error_ptr
) NULL
);
541 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
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
);
547 info_ptr
= png_create_info_struct( png_ptr
);
551 if (setjmp(wxinfo
.jmpbuf
))
554 png_uint_32 i
, width
, height
;
555 int bit_depth
, color_type
, interlace_type
;
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
);
560 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
561 png_set_expand( png_ptr
);
563 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
565 png_set_expand( png_ptr
);
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
);
573 image
->Create((int)width
, (int)height
, false /* no need to init pixels */);
578 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
582 for (i
= 0; i
< height
; i
++)
584 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
586 for ( unsigned int n
= 0; n
< i
; n
++ )
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
);
596 // loaded successfully, now init wxImage with this data
597 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
599 for ( i
= 0; i
< height
; i
++ )
607 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
623 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
627 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
632 // ----------------------------------------------------------------------------
634 // ----------------------------------------------------------------------------
636 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
638 wxPNGInfoStruct wxinfo
;
640 wxinfo
.verbose
= verbose
;
641 wxinfo
.stream
.out
= &stream
;
643 png_structp png_ptr
= png_create_write_struct( PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
647 wxLogError(_("Couldn't save PNG image."));
651 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
653 png_infop info_ptr
= png_create_info_struct(png_ptr
);
654 if (info_ptr
== NULL
)
656 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
658 wxLogError(_("Couldn't save PNG image."));
662 if (setjmp(wxinfo
.jmpbuf
))
664 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
666 wxLogError(_("Couldn't save PNG image."));
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
);
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
);
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
);
688 unsigned char *data
= (unsigned char *)malloc( image
->GetWidth()*4 );
691 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
695 for (int y
= 0; y
< image
->GetHeight(); y
++)
697 unsigned char *ptr
= image
->GetData() + (y
* image
->GetWidth() * 3);
698 for (int x
= 0; x
< image
->GetWidth(); x
++)
700 data
[(x
<< 2) + 0] = *ptr
++;
701 data
[(x
<< 2) + 1] = *ptr
++;
702 data
[(x
<< 2) + 2] = *ptr
++;
703 if ( image
->HasAlpha() )
705 data
[(x
<< 2) + 3] = image
->GetAlpha(x
, y
);
707 else if (( !image
->HasMask() ) || \
708 (data
[(x
<< 2) + 0] != image
->GetMaskRed()) || \
709 (data
[(x
<< 2) + 1] != image
->GetMaskGreen()) || \
710 (data
[(x
<< 2) + 2] != image
->GetMaskBlue()))
712 data
[(x
<< 2) + 3] = 255;
716 data
[(x
<< 2) + 3] = 0;
719 png_bytep row_ptr
= data
;
720 png_write_rows( png_ptr
, &row_ptr
, 1 );
724 png_write_end( png_ptr
, info_ptr
);
725 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
731 #pragma warning(default:4611)
734 #endif // wxUSE_STREAMS
736 #endif // wxUSE_LIBPNG