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
,
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 // ============================================================================
90 // wxPNGHandler implementation
91 // ============================================================================
93 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler
,wxImageHandler
)
97 #ifndef PNGLINKAGEMODE
99 // we need an explicit cdecl for Watcom, at least according to
101 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
103 // more testing is needed for this however, please remove this comment
104 // if you can confirm that my fix works with Watcom 11
105 #define PNGLINKAGEMODE cdecl
107 #define PNGLINKAGEMODE LINKAGEMODE
112 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
113 // First, let me describe what's the problem: libpng uses jmp_buf in
114 // its png_struct structure. Unfortunately, this structure is
115 // compiler-specific and may vary in size, so if you use libpng compiled
116 // as DLL with another compiler than the main executable, it may not work
117 // (this is for example the case with wxMGL port and SciTech MGL library
118 // that provides custom runtime-loadable libpng implementation with jmpbuf
119 // disabled altogether). Luckily, it is still possible to use setjmp() &
120 // longjmp() as long as the structure is not part of png_struct.
122 // Sadly, there's no clean way to attach user-defined data to png_struct.
123 // There is only one customizable place, png_struct.io_ptr, which is meant
124 // only for I/O routines and is set with png_set_read_fn or
125 // png_set_write_fn. The hacky part is that we use io_ptr to store
126 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
128 struct wxPNGInfoStruct
140 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
142 // ----------------------------------------------------------------------------
144 // ----------------------------------------------------------------------------
149 void PNGLINKAGEMODE
_PNG_stream_reader( png_structp png_ptr
, png_bytep data
, png_size_t length
)
151 WX_PNG_INFO(png_ptr
)->stream
.in
->Read(data
, length
);
154 void PNGLINKAGEMODE
_PNG_stream_writer( png_structp png_ptr
, png_bytep data
, png_size_t length
)
156 WX_PNG_INFO(png_ptr
)->stream
.out
->Write(data
, length
);
160 // so that the libpng doesn't send anything on stderr
162 PNGLINKAGEMODE
wx_png_error(png_structp png_ptr
, png_const_charp message
)
164 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
166 wxLogError( wxString::FromAscii(message
) );
168 #ifdef USE_FAR_KEYWORD
171 png_memcpy(jmpbuf
,info
->jmpbuf
,sizeof(jmp_buf));
175 longjmp(info
->jmpbuf
, 1);
180 PNGLINKAGEMODE
wx_png_warning(png_structp png_ptr
, png_const_charp message
)
182 wxPNGInfoStruct
*info
= WX_PNG_INFO(png_ptr
);
184 wxLogWarning( wxString::FromAscii(message
) );
189 // ----------------------------------------------------------------------------
190 // LoadFile() helpers
191 // ----------------------------------------------------------------------------
193 // determine the kind of transparency we need for this image: if the only alpha
194 // values it has are 0 and 0xff then we can simply create a mask for it, we
195 // should be ok with a simple mask but otherwise we need a full blown alpha
196 // channel in wxImage
199 // ptr the start of the data to examine
200 // x, y starting position
201 // w, h size of the image
202 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
203 // (NB: alpha always follows the colour bytes)
205 CheckTransparency(const unsigned char *ptr
,
206 png_uint_32 x
, png_uint_32 y
, png_uint_32 w
, png_uint_32 h
,
209 // suppose that a mask will suffice and check all the remaining alpha
210 // values to see if it does
212 unsigned const char *ptr2
= ptr
;
213 for ( png_uint_32 y2
= y
; y2
< h
; y2
++ )
215 for ( png_uint_32 x2
= x
+ 1; x2
< w
; x2
++ )
217 // skip the grey byte
221 if ( a2
&& a2
!= 0xff )
223 // not fully opaque nor fully transparent, hence need alpha
224 return Transparency_Alpha
;
229 // mask will be enough
230 return Transparency_Mask
;
233 unsigned char *InitAlpha(wxImage
*image
, png_uint_32 x
, png_uint_32 y
)
235 // create alpha channel
238 unsigned char *alpha
= image
->GetAlpha();
240 // set alpha for the pixels we had so far
241 for ( png_uint_32 y2
= 0; y2
<= y
; y2
++ )
243 for ( png_uint_32 x2
= 0; x2
< x
; x2
++ )
245 // all the previous pixels were opaque
254 FindMaskColour(unsigned char **lines
, png_uint_32 width
, png_uint_32 height
,
255 unsigned char& rMask
, unsigned char& gMask
, unsigned char& bMask
)
257 // choosing the colour for the mask is more
258 // difficult: we need to iterate over the entire
259 // image for this in order to choose an unused
260 // colour (this is not very efficient but what else
263 unsigned nentries
= 0;
264 unsigned char r2
, g2
, b2
;
265 for ( png_uint_32 y2
= 0; y2
< height
; y2
++ )
267 const unsigned char *p
= lines
[y2
];
268 for ( png_uint_32 x2
= 0; x2
< width
; x2
++ )
274 wxImageHistogramEntry
&
275 entry
= h
[wxImageHistogram:: MakeKey(r2
, g2
, b2
)];
277 if ( entry
.value
++ == 0 )
278 entry
.index
= nentries
++;
282 if ( !h
.FindFirstUnusedColour(&rMask
, &gMask
, &bMask
) )
284 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
286 // use a fixed mask colour and we'll fudge
287 // the real pixels with this colour (see
295 // ----------------------------------------------------------------------------
297 // ----------------------------------------------------------------------------
299 bool wxPNGHandler::DoCanRead( wxInputStream
& stream
)
301 unsigned char hdr
[4];
303 if ( !stream
.Read(hdr
, WXSIZEOF(hdr
)) )
306 return memcmp(hdr
, "\211PNG", WXSIZEOF(hdr
)) == 0;
309 // convert data from RGB to wxImage format
311 void CopyDataFromPNG(wxImage
*image
,
312 unsigned char **lines
,
317 Transparency transparency
= Transparency_None
;
319 // only non NULL if transparency == Transparency_Alpha
320 unsigned char *alpha
= NULL
;
322 // RGB of the mask colour if transparency == Transparency_Mask
323 // (but init them anyhow to avoid compiler warnings)
324 unsigned char rMask
= 0,
328 unsigned char *ptrDst
= image
->GetData();
329 if ( !(color_type
& PNG_COLOR_MASK_COLOR
) )
331 // grey image: GAGAGA... where G == grey component and A == alpha
332 for ( png_uint_32 y
= 0; y
< height
; y
++ )
334 const unsigned char *ptrSrc
= lines
[y
];
335 for ( png_uint_32 x
= 0; x
< width
; x
++ )
337 unsigned char g
= *ptrSrc
++;
338 unsigned char a
= *ptrSrc
++;
340 // the first time we encounter a transparent pixel we must
341 // decide about what to do about them
342 if ( a
!= 0xff && transparency
== Transparency_None
)
344 // we'll need at least the mask for this image and
345 // maybe even full alpha channel info: the former is
346 // only enough if we have alpha values of 0 and 0xff
347 // only, otherwisewe need the latter
348 transparency
= CheckTransparency
356 if ( transparency
== Transparency_Mask
)
358 // let's choose this colour for the mask: this is
359 // not a problem here as all the other pixels are
360 // grey, i.e. R == G == B which is not the case for
361 // this one so no confusion is possible
366 else // transparency == Transparency_Alpha
368 alpha
= InitAlpha(image
, x
, y
);
372 switch ( transparency
)
374 case Transparency_Alpha
:
378 case Transparency_None
:
384 case Transparency_Mask
:
392 else // colour image: RGBRGB...
394 for ( png_uint_32 y
= 0; y
< height
; y
++ )
396 const unsigned char *ptrSrc
= lines
[y
];
397 for ( png_uint_32 x
= 0; x
< width
; x
++ )
399 unsigned char r
= *ptrSrc
++;
400 unsigned char g
= *ptrSrc
++;
401 unsigned char b
= *ptrSrc
++;
402 unsigned char a
= *ptrSrc
++;
404 // the logic here is the same as for the grey case except
406 if ( a
!= 0xff && transparency
== Transparency_None
)
408 transparency
= CheckTransparency
416 if ( transparency
== Transparency_Mask
)
418 FindMaskColour(lines
, width
, height
,
419 rMask
, gMask
, bMask
);
421 else // transparency == Transparency_Alpha
423 alpha
= InitAlpha(image
, x
, y
);
428 switch ( transparency
)
430 case Transparency_Alpha
:
434 case Transparency_None
:
440 case Transparency_Mask
:
441 // if we couldn't find a unique colour for the mask, we
442 // can have real pixels with the same value as the mask
443 // and it's better to slightly change their colour than
444 // to make them transparent
445 if ( r
== rMask
&& g
== gMask
&& b
== bMask
)
458 if ( transparency
== Transparency_Mask
)
460 image
->SetMaskColour(rMask
, gMask
, bMask
);
464 // temporarily disable the warning C4611 (interaction between '_setjmp' and
465 // C++ object destruction is non-portable) - I don't see any dtors here
467 #pragma warning(disable:4611)
471 wxPNGHandler::LoadFile(wxImage
*image
,
472 wxInputStream
& stream
,
476 // VZ: as this function uses setjmp() the only fool proof error handling
477 // method is to use goto (setjmp is not really C++ dtors friendly...)
479 unsigned char **lines
= NULL
;
480 png_infop info_ptr
= (png_infop
) NULL
;
481 wxPNGInfoStruct wxinfo
;
483 wxinfo
.verbose
= verbose
;
484 wxinfo
.stream
.in
= &stream
;
488 png_structp png_ptr
= png_create_read_struct( PNG_LIBPNG_VER_STRING
,
490 (png_error_ptr
) NULL
,
491 (png_error_ptr
) NULL
);
495 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
497 // NB: please see the comment near wxPNGInfoStruct declaration for
498 // explanation why this line is mandatory
499 png_set_read_fn( png_ptr
, &wxinfo
, _PNG_stream_reader
);
501 info_ptr
= png_create_info_struct( png_ptr
);
505 if (setjmp(wxinfo
.jmpbuf
))
508 png_uint_32 i
, width
, height
;
509 int bit_depth
, color_type
, interlace_type
;
511 png_read_info( png_ptr
, info_ptr
);
512 png_get_IHDR( png_ptr
, info_ptr
, &width
, &height
, &bit_depth
, &color_type
, &interlace_type
, (int*) NULL
, (int*) NULL
);
514 if (color_type
== PNG_COLOR_TYPE_PALETTE
)
515 png_set_expand( png_ptr
);
517 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
519 png_set_expand( png_ptr
);
521 png_set_strip_16( png_ptr
);
522 png_set_packing( png_ptr
);
523 if (png_get_valid( png_ptr
, info_ptr
, PNG_INFO_tRNS
))
524 png_set_expand( png_ptr
);
525 png_set_filler( png_ptr
, 0xff, PNG_FILLER_AFTER
);
527 image
->Create( (int)width
, (int)height
);
532 lines
= (unsigned char **)malloc( (size_t)(height
* sizeof(unsigned char *)) );
536 for (i
= 0; i
< height
; i
++)
538 if ((lines
[i
] = (unsigned char *)malloc( (size_t)(width
* (sizeof(unsigned char) * 4)))) == NULL
)
540 for ( unsigned int n
= 0; n
< i
; n
++ )
546 png_read_image( png_ptr
, lines
);
547 png_read_end( png_ptr
, info_ptr
);
548 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
550 // loaded successfully, now init wxImage with this data
551 CopyDataFromPNG(image
, lines
, width
, height
, color_type
);
553 for ( i
= 0; i
< height
; i
++ )
561 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
577 png_destroy_read_struct( &png_ptr
, &info_ptr
, (png_infopp
) NULL
);
581 png_destroy_read_struct( &png_ptr
, (png_infopp
) NULL
, (png_infopp
) NULL
);
586 // ----------------------------------------------------------------------------
588 // ----------------------------------------------------------------------------
590 bool wxPNGHandler::SaveFile( wxImage
*image
, wxOutputStream
& stream
, bool verbose
)
592 wxPNGInfoStruct wxinfo
;
594 wxinfo
.verbose
= verbose
;
595 wxinfo
.stream
.out
= &stream
;
597 png_structp png_ptr
= png_create_write_struct( PNG_LIBPNG_VER_STRING
, NULL
, NULL
, NULL
);
601 wxLogError(_("Couldn't save PNG image."));
605 png_set_error_fn(png_ptr
, (png_voidp
)NULL
, wx_png_error
, wx_png_warning
);
607 png_infop info_ptr
= png_create_info_struct(png_ptr
);
608 if (info_ptr
== NULL
)
610 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
612 wxLogError(_("Couldn't save PNG image."));
616 if (setjmp(wxinfo
.jmpbuf
))
618 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
620 wxLogError(_("Couldn't save PNG image."));
624 // NB: please see the comment near wxPNGInfoStruct declaration for
625 // explanation why this line is mandatory
626 png_set_write_fn( png_ptr
, &wxinfo
, _PNG_stream_writer
, NULL
);
628 png_set_IHDR( png_ptr
, info_ptr
, image
->GetWidth(), image
->GetHeight(), 8,
629 PNG_COLOR_TYPE_RGB_ALPHA
, PNG_INTERLACE_NONE
,
630 PNG_COMPRESSION_TYPE_BASE
, PNG_FILTER_TYPE_BASE
);
637 png_set_sBIT( png_ptr
, info_ptr
, &sig_bit
);
638 png_write_info( png_ptr
, info_ptr
);
639 png_set_shift( png_ptr
, &sig_bit
);
640 png_set_packing( png_ptr
);
642 unsigned char *data
= (unsigned char *)malloc( image
->GetWidth()*4 );
645 png_destroy_write_struct( &png_ptr
, (png_infopp
)NULL
);
649 for (int y
= 0; y
< image
->GetHeight(); y
++)
651 unsigned char *ptr
= image
->GetData() + (y
* image
->GetWidth() * 3);
652 for (int x
= 0; x
< image
->GetWidth(); x
++)
654 data
[(x
<< 2) + 0] = *ptr
++;
655 data
[(x
<< 2) + 1] = *ptr
++;
656 data
[(x
<< 2) + 2] = *ptr
++;
657 if (( !image
->HasMask() ) || \
658 (data
[(x
<< 2) + 0] != image
->GetMaskRed()) || \
659 (data
[(x
<< 2) + 1] != image
->GetMaskGreen()) || \
660 (data
[(x
<< 2) + 2] != image
->GetMaskBlue()))
662 data
[(x
<< 2) + 3] = 255;
666 data
[(x
<< 2) + 3] = 0;
669 png_bytep row_ptr
= data
;
670 png_write_rows( png_ptr
, &row_ptr
, 1 );
674 png_write_end( png_ptr
, info_ptr
);
675 png_destroy_write_struct( &png_ptr
, (png_infopp
)&info_ptr
);
681 #pragma warning(default:4611)
684 #endif // wxUSE_STREAMS
686 #endif // wxUSE_LIBPNG