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 // ----------------------------------------------------------------------------
192 // determine the kind of transparency we need for this image: if the only alpha
193 // values it has are 0 and 0xff then we can simply create a mask for it, we
194 // should be ok with a simple mask but otherwise we need a full blown alpha
195 // channel in wxImage
198 // ptr the start of the data to examine
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(const unsigned char *ptr
,
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
211 unsigned const char *ptr2
= ptr
;
212 for ( png_uint_32 y2
= y
; y2
< h
; y2
++ )
214 for ( png_uint_32 x2
= x
+ 1; x2
< w
; x2
++ )
216 // skip the grey byte
220 if ( a2
&& a2
!= 0xff )
222 // not fully opaque nor fully transparent, hence need alpha
223 return Transparency_Alpha
;
228 // mask will be enough
229 return Transparency_Mask
;
232 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
234 // create alpha channel
237 unsigned char *alpha
= image
->GetAlpha();
239 // set alpha for the pixels we had so far
240 for ( png_uint_32 y2
= 0; y2
<= y
; y2
++ )
242 for ( png_uint_32 x2
= 0; x2
< x
; x2
++ )
244 // all the previous pixels were opaque
253 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
254 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
256 // choosing the colour for the mask is more
257 // difficult: we need to iterate over the entire
258 // image for this in order to choose an unused
259 // colour (this is not very efficient but what else
262 unsigned nentries
= 0;
263 unsigned char r2
, g2
, b2
;
264 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
266 const unsigned char *p
= lines
[y2
];
267 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
273 wxImageHistogramEntry
&
274 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
276 if ( entry
.value
++ == 0 )
277 entry
.index
= nentries
++;
281 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
283 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
285 // use a fixed mask colour and we'll fudge
286 // the real pixels with this colour (see
294 // ----------------------------------------------------------------------------
296 // ----------------------------------------------------------------------------
298 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
300 unsigned char hdr
[4];
302 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
305 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
308 // convert data from RGB to wxImage format
310 void CopyDataFromPNG(wxImage
*image
,
311 unsigned char **lines
,
316 Transparency transparency
= Transparency_None
;
318 // only non NULL if transparency == Transparency_Alpha
319 unsigned char *alpha
= NULL
;
321 // RGB of the mask colour if transparency == Transparency_Mask
322 // (but init them anyhow to avoid compiler warnings)
323 unsigned char rMask
= 0,
327 unsigned char *ptrDst
= image
->GetData();
328 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
330 // grey image: GAGAGA... where G == grey component and A == alpha
331 for ( png_uint_32 y
= 0; y
< height
; y
++ )
333 const unsigned char *ptrSrc
= lines
[y
];
334 for ( png_uint_32 x
= 0; x
< width
; x
++ )
336 unsigned char g
= *ptrSrc
++;
337 unsigned char a
= *ptrSrc
++;
339 // the first time we encounter a transparent pixel we must
340 // decide about what to do about them
341 if ( a
!= 0xff && transparency
== Transparency_None
)
343 // we'll need at least the mask for this image and
344 // maybe even full alpha channel info: the former is
345 // only enough if we have alpha values of 0 and 0xff
346 // only, otherwisewe need the latter
347 transparency
= CheckTransparency
355 if ( transparency
== Transparency_Mask
)
357 // let's choose this colour for the mask: this is
358 // not a problem here as all the other pixels are
359 // grey, i.e. R == G == B which is not the case for
360 // this one so no confusion is possible
365 else // transparency == Transparency_Alpha
367 alpha
= InitAlpha(image
, x
, y
);
371 switch ( transparency
)
373 case Transparency_Alpha
:
377 case Transparency_None
:
383 case Transparency_Mask
:
391 else // colour image: RGBRGB...
393 for ( png_uint_32 y
= 0; y
< height
; y
++ )
395 const unsigned char *ptrSrc
= lines
[y
];
396 for ( png_uint_32 x
= 0; x
< width
; x
++ )
398 unsigned char r
= *ptrSrc
++;
399 unsigned char g
= *ptrSrc
++;
400 unsigned char b
= *ptrSrc
++;
401 unsigned char a
= *ptrSrc
++;
403 // the logic here is the same as for the grey case except
405 if ( a
!= 0xff && transparency
== Transparency_None
)
407 transparency
= CheckTransparency
415 if ( transparency
== Transparency_Mask
)
417 FindMaskColour(lines
, width
, height
,
418 rMask
, gMask
, bMask
);
420 else // transparency == Transparency_Alpha
422 alpha
= InitAlpha(image
, x
, y
);
427 switch ( transparency
)
429 case Transparency_Alpha
:
433 case Transparency_None
:
439 case Transparency_Mask
:
440 // if we couldn't find a unique colour for the mask, we
441 // can have real pixels with the same value as the mask
442 // and it's better to slightly change their colour than
443 // to make them transparent
444 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
457 if ( transparency
== Transparency_Mask
)
459 image
->SetMaskColour(rMask
, gMask
, bMask
);
463 // temporarily disable the warning C4611 (interaction between '_setjmp' and
464 // C++ object destruction is non-portable) - I don't see any dtors here
466 #pragma warning(disable:4611)
470 wxPNGHandler::LoadFile(wxImage
*image
,
471 wxInputStream
& stream
,
475 // VZ: as this function uses setjmp() the only fool proof error handling
476 // method is to use goto (setjmp is not really C++ dtors friendly...)
478 unsigned char **lines
= NULL
;
479 png_infop info_ptr
= (png_infop
) NULL
;
480 wxPNGInfoStruct wxinfo
;
482 wxinfo
.verbose
= verbose
;
483 wxinfo
.stream
.in
= &stream
;
487 png_structp png_ptr
= png_create_read_struct( PNG_LIBPNG_VER_STRING
,
489 (png_error_ptr
) NULL
,
490 (png_error_ptr
) NULL
);
494 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
496 // NB: please see the comment near wxPNGInfoStruct declaration for
497 // explanation why this line is mandatory
498 png_set_read_fn( png_ptr
, &wxinfo
, _PNG_stream_reader
);
500 info_ptr
= png_create_info_struct( png_ptr
);
504 if (setjmp(wxinfo
.jmpbuf
))
507 png_uint_32 i
, width
, height
;
508 int bit_depth
, color_type
, interlace_type
;
510 png_read_info( png_ptr
, info_ptr
);
511 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
513 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
514 png_set_expand( png_ptr
);
516 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
518 png_set_expand( png_ptr
);
520 png_set_strip_16( png_ptr
);
521 png_set_packing( png_ptr
);
522 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
523 png_set_expand( png_ptr
);
524 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
526 image
->Create( (int)width
, (int)height
);
531 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
535 for (i
= 0; i
< height
; i
++)
537 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
539 for ( unsigned int n
= 0; n
< i
; n
++ )
545 png_read_image( png_ptr
, lines
);
546 png_read_end( png_ptr
, info_ptr
);
547 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
549 // loaded successfully, now init wxImage with this data
550 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
552 for ( i
= 0; i
< height
; i
++ )
560 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
576 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
580 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
585 // ----------------------------------------------------------------------------
587 // ----------------------------------------------------------------------------
589 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
591 wxPNGInfoStruct wxinfo
;
593 wxinfo
.verbose
= verbose
;
594 wxinfo
.stream
.out
= &stream
;
596 png_structp png_ptr
= png_create_write_struct( PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
600 wxLogError(_("Couldn't save PNG image."));
604 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
606 png_infop info_ptr
= png_create_info_struct(png_ptr
);
607 if (info_ptr
== NULL
)
609 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
611 wxLogError(_("Couldn't save PNG image."));
615 if (setjmp(wxinfo
.jmpbuf
))
617 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
619 wxLogError(_("Couldn't save PNG image."));
623 // NB: please see the comment near wxPNGInfoStruct declaration for
624 // explanation why this line is mandatory
625 png_set_write_fn( png_ptr
, &wxinfo
, _PNG_stream_writer
, NULL
);
627 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(), 8,
628 PNG_COLOR_TYPE_RGB_ALPHA
, PNG_INTERLACE_NONE
,
629 PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
636 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
637 png_write_info( png_ptr
, info_ptr
);
638 png_set_shift( png_ptr
, &sig_bit
);
639 png_set_packing( png_ptr
);
641 unsigned char *data
= (unsigned char *)malloc( image
->GetWidth()*4 );
644 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
648 for (int y
= 0; y
< image
->GetHeight(); y
++)
650 unsigned char *ptr
= image
->GetData() + (y
* image
->GetWidth() * 3);
651 for (int x
= 0; x
< image
->GetWidth(); x
++)
653 data
[(x
<< 2) + 0] = *ptr
++;
654 data
[(x
<< 2) + 1] = *ptr
++;
655 data
[(x
<< 2) + 2] = *ptr
++;
656 if (( !image
->HasMask() ) || \
657 (data
[(x
<< 2) + 0] != image
->GetMaskRed()) || \
658 (data
[(x
<< 2) + 1] != image
->GetMaskGreen()) || \
659 (data
[(x
<< 2) + 2] != image
->GetMaskBlue()))
661 data
[(x
<< 2) + 3] = 255;
665 data
[(x
<< 2) + 3] = 0;
668 png_bytep row_ptr
= data
;
669 png_write_rows( png_ptr
, &row_ptr
, 1 );
673 png_write_end( png_ptr
, info_ptr
);
674 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
680 #pragma warning(default:4611)
683 #endif // wxUSE_STREAMS
685 #endif // wxUSE_LIBPNG