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 // ============================================================================
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(const unsigned char *ptr
,
78 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
);
80 // init the alpha channel for the image and fill it with 1s up to (x, y)
81 static unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
);
83 // find a free colour for the mask in the PNG data array
85 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
86 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
);
88 // ============================================================================
89 // wxPNGHandler implementation
90 // ============================================================================
92 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
96 #ifndef PNGLINKAGEMODE
98 // we need an explicit cdecl for Watcom, at least according to
100 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
102 // more testing is needed for this however, please remove this comment
103 // if you can confirm that my fix works with Watcom 11
104 #define PNGLINKAGEMODE cdecl
106 #define PNGLINKAGEMODE LINKAGEMODE
111 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
112 // First, let me describe what's the problem: libpng uses jmp_buf in
113 // its png_struct structure. Unfortunately, this structure is
114 // compiler-specific and may vary in size, so if you use libpng compiled
115 // as DLL with another compiler than the main executable, it may not work
116 // (this is for example the case with wxMGL port and SciTech MGL library
117 // that provides custom runtime-loadable libpng implementation with jmpbuf
118 // disabled altogether). Luckily, it is still possible to use setjmp() &
119 // longjmp() as long as the structure is not part of png_struct.
121 // Sadly, there's no clean way to attach user-defined data to png_struct.
122 // There is only one customizable place, png_struct.io_ptr, which is meant
123 // only for I/O routines and is set with png_set_read_fn or
124 // png_set_write_fn. The hacky part is that we use io_ptr to store
125 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
127 struct wxPNGInfoStruct
139 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
148 void PNGLINKAGEMODE
_PNG_stream_reader( png_structp png_ptr
, png_bytep data
, png_size_t length
)
150 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
153 void PNGLINKAGEMODE
_PNG_stream_writer( png_structp png_ptr
, png_bytep data
, png_size_t length
)
155 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
159 // so that the libpng doesn't send anything on stderr
161 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
163 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
165 wxLogError( wxString::FromAscii(message
) );
167 #ifdef USE_FAR_KEYWORD
170 png_memcpy(jmpbuf
,info
->jmpbuf
,sizeof(jmp_buf));
174 longjmp(info
->jmpbuf
, 1);
179 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
181 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
183 wxLogWarning( wxString::FromAscii(message
) );
188 // ----------------------------------------------------------------------------
189 // LoadFile() helpers
190 // ----------------------------------------------------------------------------
193 CheckTransparency(const unsigned char *ptr
,
194 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
)
196 // suppose that a mask will suffice
197 Transparency transparency
= Transparency_Mask
;
199 // and check all the remaining alpha values to see if it does
201 unsigned const char *ptr2
= ptr
;
202 for ( png_uint_32 y2
= y
; y2
< h
; y2
++ )
204 for ( png_uint_32 x2
= x
+ 1; x2
< w
; x2
++ )
206 // skip the grey byte
209 if ( a2
&& a2
!= 0xff )
211 // not fully opeaque nor fully transparent, hence need alpha
212 transparency
= Transparency_Alpha
;
219 if ( transparency
== Transparency_Alpha
)
221 // no need to continue
229 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
231 // create alpha channel
234 unsigned char *alpha
= image
->GetAlpha();
236 // set alpha for the pixels we had so far
237 for ( png_uint_32 y2
= 0; y2
<= y
; y2
++ )
239 for ( png_uint_32 x2
= 0; x2
< x
; x2
++ )
241 // all the previous pixels were opaque
250 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
251 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
253 // choosing the colour for the mask is more
254 // difficult: we need to iterate over the entire
255 // image for this in order to choose an unused
256 // colour (this is not very efficient but what else
259 unsigned nentries
= 0;
260 unsigned char r2
, g2
, b2
;
261 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
263 const unsigned char *p
= lines
[y2
];
264 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
270 wxImageHistogramEntry
&
271 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
273 if ( entry
.value
++ == 0 )
274 entry
.index
= nentries
++;
278 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
280 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
282 // use a fixed mask colour and we'll fudge
283 // the real pixels with this colour (see
291 // ----------------------------------------------------------------------------
293 // ----------------------------------------------------------------------------
295 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
297 unsigned char hdr
[4];
299 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
302 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
305 // convert data from RGB to wxImage format
307 void CopyDataFromPNG(wxImage
*image
,
308 unsigned char **lines
,
313 Transparency transparency
= Transparency_None
;
315 // only non NULL if transparency == Transparency_Alpha
316 unsigned char *alpha
= NULL
;
318 // RGB of the mask colour if transparency == Transparency_Mask
319 // (but init them anyhow to avoid compiler warnings)
320 unsigned char rMask
= 0,
324 unsigned char *ptrDst
= image
->GetData();
325 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
327 // grey image: GAGAGA... where G == grey component and A == alpha
328 for ( png_uint_32 y
= 0; y
< height
; y
++ )
330 const unsigned char *ptrSrc
= lines
[y
];
331 for ( png_uint_32 x
= 0; x
< width
; x
++ )
333 unsigned char g
= *ptrSrc
++;
334 unsigned char a
= *ptrSrc
++;
336 // the first time we encounter a transparent pixel we must
337 // decide about what to do about them
338 if ( a
!= 0xff && transparency
== Transparency_None
)
340 // we'll need at least the mask for this image and
341 // maybe even full alpha channel info: the former is
342 // only enough if we have alpha values of 0 and 0xff
343 // only, otherwisewe need the latter
344 transparency
= CheckTransparency(ptrSrc
, x
, y
,
347 if ( transparency
== Transparency_Mask
)
349 // let's choose this colour for the mask: this is
350 // not a problem here as all the other pixels are
351 // grey, i.e. R == G == B which is not the case for
352 // this one so no confusion is possible
357 else // transparency == Transparency_Alpha
359 alpha
= InitAlpha(image
, x
, y
);
363 switch ( transparency
)
365 case Transparency_Alpha
:
369 case Transparency_None
:
375 case Transparency_Mask
:
383 else // colour image: RGBRGB...
385 for ( png_uint_32 y
= 0; y
< height
; y
++ )
387 const unsigned char *ptrSrc
= lines
[y
];
388 for ( png_uint_32 x
= 0; x
< width
; x
++ )
390 unsigned char r
= *ptrSrc
++;
391 unsigned char g
= *ptrSrc
++;
392 unsigned char b
= *ptrSrc
++;
393 unsigned char a
= *ptrSrc
++;
395 // the logic here is the same as for the grey case except
397 if ( a
!= 0xff && transparency
== Transparency_None
)
399 transparency
= CheckTransparency(ptrSrc
, x
, y
,
402 if ( transparency
== Transparency_Mask
)
404 FindMaskColour(lines
, width
, height
,
405 rMask
, gMask
, bMask
);
407 else // transparency == Transparency_Alpha
409 alpha
= InitAlpha(image
, x
, y
);
414 switch ( transparency
)
416 case Transparency_Alpha
:
420 case Transparency_None
:
426 case Transparency_Mask
:
427 // if we couldn't find a unique colour for the mask, we
428 // can have real pixels with the same value as the mask
429 // and it's better to slightly change their colour than
430 // to make them transparent
431 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
444 if ( transparency
== Transparency_Mask
)
446 image
->SetMaskColour(rMask
, gMask
, bMask
);
450 // temporarily disable the warning C4611 (interaction between '_setjmp' and
451 // C++ object destruction is non-portable) - I don't see any dtors here
453 #pragma warning(disable:4611)
457 wxPNGHandler::LoadFile(wxImage
*image
,
458 wxInputStream
& stream
,
462 // VZ: as this function uses setjmp() the only fool proof error handling
463 // method is to use goto (setjmp is not really C++ dtors friendly...)
465 unsigned char **lines
= NULL
;
466 png_infop info_ptr
= (png_infop
) NULL
;
467 wxPNGInfoStruct wxinfo
;
469 wxinfo
.verbose
= verbose
;
470 wxinfo
.stream
.in
= &stream
;
474 png_structp png_ptr
= png_create_read_struct( PNG_LIBPNG_VER_STRING
,
476 (png_error_ptr
) NULL
,
477 (png_error_ptr
) NULL
);
481 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
483 // NB: please see the comment near wxPNGInfoStruct declaration for
484 // explanation why this line is mandatory
485 png_set_read_fn( png_ptr
, &wxinfo
, _PNG_stream_reader
);
487 info_ptr
= png_create_info_struct( png_ptr
);
491 if (setjmp(wxinfo
.jmpbuf
))
494 png_uint_32 i
, width
, height
;
495 int bit_depth
, color_type
, interlace_type
;
497 png_read_info( png_ptr
, info_ptr
);
498 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
500 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
501 png_set_expand( png_ptr
);
503 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
505 png_set_expand( png_ptr
);
507 png_set_strip_16( png_ptr
);
508 png_set_packing( png_ptr
);
509 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
510 png_set_expand( png_ptr
);
511 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
513 image
->Create( (int)width
, (int)height
);
518 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
522 for (i
= 0; i
< height
; i
++)
524 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
526 for ( unsigned int n
= 0; n
< i
; n
++ )
532 png_read_image( png_ptr
, lines
);
533 png_read_end( png_ptr
, info_ptr
);
534 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
536 // loaded successfully, now init wxImage with this data
537 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
539 for ( i
= 0; i
< height
; i
++ )
547 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
563 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
567 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
572 // ----------------------------------------------------------------------------
574 // ----------------------------------------------------------------------------
576 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
578 wxPNGInfoStruct wxinfo
;
580 wxinfo
.verbose
= verbose
;
581 wxinfo
.stream
.out
= &stream
;
583 png_structp png_ptr
= png_create_write_struct( PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
587 wxLogError(_("Couldn't save PNG image."));
591 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
593 png_infop info_ptr
= png_create_info_struct(png_ptr
);
594 if (info_ptr
== NULL
)
596 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
598 wxLogError(_("Couldn't save PNG image."));
602 if (setjmp(wxinfo
.jmpbuf
))
604 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
606 wxLogError(_("Couldn't save PNG image."));
610 // NB: please see the comment near wxPNGInfoStruct declaration for
611 // explanation why this line is mandatory
612 png_set_write_fn( png_ptr
, &wxinfo
, _PNG_stream_writer
, NULL
);
614 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(), 8,
615 PNG_COLOR_TYPE_RGB_ALPHA
, PNG_INTERLACE_NONE
,
616 PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
623 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
624 png_write_info( png_ptr
, info_ptr
);
625 png_set_shift( png_ptr
, &sig_bit
);
626 png_set_packing( png_ptr
);
628 unsigned char *data
= (unsigned char *)malloc( image
->GetWidth()*4 );
631 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
635 for (int y
= 0; y
< image
->GetHeight(); y
++)
637 unsigned char *ptr
= image
->GetData() + (y
* image
->GetWidth() * 3);
638 for (int x
= 0; x
< image
->GetWidth(); x
++)
640 data
[(x
<< 2) + 0] = *ptr
++;
641 data
[(x
<< 2) + 1] = *ptr
++;
642 data
[(x
<< 2) + 2] = *ptr
++;
643 if (( !image
->HasMask() ) || \
644 (data
[(x
<< 2) + 0] != image
->GetMaskRed()) || \
645 (data
[(x
<< 2) + 1] != image
->GetMaskGreen()) || \
646 (data
[(x
<< 2) + 2] != image
->GetMaskBlue()))
648 data
[(x
<< 2) + 3] = 255;
652 data
[(x
<< 2) + 3] = 0;
655 png_bytep row_ptr
= data
;
656 png_write_rows( png_ptr
, &row_ptr
, 1 );
660 png_write_end( png_ptr
, info_ptr
);
661 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
667 #pragma warning(default:4611)
670 #endif // wxUSE_STREAMS
672 #endif // wxUSE_LIBPNG