added support for reading alpha channel
[wxWidgets.git] / src / common / imagpng.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagepng.cpp
3 // Purpose: wxImage PNG handler
4 // Author: Robert Roebling
5 // RCS-ID: $Id$
6 // Copyright: (c) Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // ============================================================================
11 // declarations
12 // ============================================================================
13
14 #ifdef __GNUG__
15 #pragma implementation "imagpng.h"
16 #endif
17
18 // ----------------------------------------------------------------------------
19 // headers
20 // ----------------------------------------------------------------------------
21
22 // For compilers that support precompilation, includes "wx.h".
23 #include "wx/wxprec.h"
24
25 #ifdef __BORLANDC__
26 #pragma hdrstop
27 #endif
28
29 #ifndef WX_PRECOMP
30 #include "wx/defs.h"
31 #endif
32
33 #if wxUSE_IMAGE && wxUSE_LIBPNG
34
35 #include "wx/imagpng.h"
36 #include "wx/bitmap.h"
37 #include "wx/debug.h"
38 #include "wx/log.h"
39 #include "wx/app.h"
40 #include "png.h"
41 #include "wx/filefn.h"
42 #include "wx/wfstream.h"
43 #include "wx/intl.h"
44 #include "wx/module.h"
45
46 // For memcpy
47 #include <string.h>
48
49 #ifdef __SALFORDC__
50 #ifdef FAR
51 #undef FAR
52 #endif
53 #endif
54
55 // ----------------------------------------------------------------------------
56 // constants
57 // ----------------------------------------------------------------------------
58
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
63 enum Transparency
64 {
65 Transparency_None,
66 Transparency_Mask,
67 Transparency_Alpha
68 };
69
70 // ----------------------------------------------------------------------------
71 // local functions
72 // ----------------------------------------------------------------------------
73
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
76 static Transparency
77 CheckTransparency(const unsigned char *ptr,
78 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h);
79
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);
82
83 // find a free colour for the mask in the PNG data array
84 static void
85 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
86 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask);
87
88 // ============================================================================
89 // wxPNGHandler implementation
90 // ============================================================================
91
92 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler)
93
94 #if wxUSE_STREAMS
95
96 #ifndef PNGLINKAGEMODE
97 #ifdef __WATCOMC__
98 // we need an explicit cdecl for Watcom, at least according to
99 //
100 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
101 //
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
105 #else
106 #define PNGLINKAGEMODE LINKAGEMODE
107 #endif
108 #endif
109
110
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.
120 //
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.
126
127 struct wxPNGInfoStruct
128 {
129 jmp_buf jmpbuf;
130 bool verbose;
131
132 union
133 {
134 wxInputStream *in;
135 wxOutputStream *out;
136 } stream;
137 };
138
139 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
140
141 // ----------------------------------------------------------------------------
142 // helper functions
143 // ----------------------------------------------------------------------------
144
145 extern "C"
146 {
147
148 void PNGLINKAGEMODE _PNG_stream_reader( png_structp png_ptr, png_bytep data, png_size_t length )
149 {
150 WX_PNG_INFO(png_ptr)->stream.in->Read(data, length);
151 }
152
153 void PNGLINKAGEMODE _PNG_stream_writer( png_structp png_ptr, png_bytep data, png_size_t length )
154 {
155 WX_PNG_INFO(png_ptr)->stream.out->Write(data, length);
156 }
157
158 // from pngerror.c
159 // so that the libpng doesn't send anything on stderr
160 void
161 PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message)
162 {
163 wxPNGInfoStruct *info = WX_PNG_INFO(png_ptr);
164 if (info->verbose)
165 wxLogError( wxString::FromAscii(message) );
166
167 #ifdef USE_FAR_KEYWORD
168 {
169 jmp_buf jmpbuf;
170 png_memcpy(jmpbuf,info->jmpbuf,sizeof(jmp_buf));
171 longjmp(jmpbuf, 1);
172 }
173 #else
174 longjmp(info->jmpbuf, 1);
175 #endif
176 }
177
178 void
179 PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message)
180 {
181 wxPNGInfoStruct *info = WX_PNG_INFO(png_ptr);
182 if (info->verbose)
183 wxLogWarning( wxString::FromAscii(message) );
184 }
185
186 } // extern "C"
187
188 // ----------------------------------------------------------------------------
189 // LoadFile() helpers
190 // ----------------------------------------------------------------------------
191
192 Transparency
193 CheckTransparency(const unsigned char *ptr,
194 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h)
195 {
196 // suppose that a mask will suffice
197 Transparency transparency = Transparency_Mask;
198
199 // and check all the remaining alpha values to see if it does
200 unsigned char a2;
201 unsigned const char *ptr2 = ptr;
202 for ( png_uint_32 y2 = y; y2 < h; y2++ )
203 {
204 for ( png_uint_32 x2 = x + 1; x2 < w; x2++ )
205 {
206 // skip the grey byte
207 a2 = *++ptr2;
208
209 if ( a2 && a2 != 0xff )
210 {
211 // not fully opeaque nor fully transparent, hence need alpha
212 transparency = Transparency_Alpha;
213 break;
214 }
215
216 ++ptr2;
217 }
218
219 if ( transparency == Transparency_Alpha )
220 {
221 // no need to continue
222 break;
223 }
224 }
225
226 return transparency;
227 }
228
229 unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y)
230 {
231 // create alpha channel
232 image->SetAlpha();
233
234 unsigned char *alpha = image->GetAlpha();
235
236 // set alpha for the pixels we had so far
237 for ( png_uint_32 y2 = 0; y2 <= y; y2++ )
238 {
239 for ( png_uint_32 x2 = 0; x2 < x; x2++ )
240 {
241 // all the previous pixels were opaque
242 *alpha++ = 0xff;
243 }
244 }
245
246 return alpha;
247 }
248
249 void
250 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
251 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask)
252 {
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
257 // can we do?)
258 wxImageHistogram h;
259 unsigned nentries = 0;
260 unsigned char r2, g2, b2;
261 for ( png_uint_32 y2 = 0; y2 < height; y2++ )
262 {
263 const unsigned char *p = lines[y2];
264 for ( png_uint_32 x2 = 0; x2 < width; x2++ )
265 {
266 r2 = *p++;
267 g2 = *p++;
268 b2 = *p++;
269
270 wxImageHistogramEntry&
271 entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)];
272
273 if ( entry.value++ == 0 )
274 entry.index = nentries++;
275 }
276 }
277
278 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
279 {
280 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
281
282 // use a fixed mask colour and we'll fudge
283 // the real pixels with this colour (see
284 // below)
285 rMask = 0xfe;
286 gMask = 0;
287 bMask = 0xff;
288 }
289 }
290
291 // ----------------------------------------------------------------------------
292 // reading PNGs
293 // ----------------------------------------------------------------------------
294
295 bool wxPNGHandler::DoCanRead( wxInputStream& stream )
296 {
297 unsigned char hdr[4];
298
299 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
300 return FALSE;
301
302 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
303 }
304
305 // convert data from RGB to wxImage format
306 static
307 void CopyDataFromPNG(wxImage *image,
308 unsigned char **lines,
309 png_uint_32 width,
310 png_uint_32 height,
311 int color_type)
312 {
313 Transparency transparency = Transparency_None;
314
315 // only non NULL if transparency == Transparency_Alpha
316 unsigned char *alpha = NULL;
317
318 // RGB of the mask colour if transparency == Transparency_Mask
319 // (but init them anyhow to avoid compiler warnings)
320 unsigned char rMask = 0,
321 gMask = 0,
322 bMask = 0;
323
324 unsigned char *ptrDst = image->GetData();
325 if ( !(color_type & PNG_COLOR_MASK_COLOR) )
326 {
327 // grey image: GAGAGA... where G == grey component and A == alpha
328 for ( png_uint_32 y = 0; y < height; y++ )
329 {
330 const unsigned char *ptrSrc = lines[y];
331 for ( png_uint_32 x = 0; x < width; x++ )
332 {
333 unsigned char g = *ptrSrc++;
334 unsigned char a = *ptrSrc++;
335
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 )
339 {
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,
345 width, height);
346
347 if ( transparency == Transparency_Mask )
348 {
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
353 rMask = 0xff;
354 gMask = 0;
355 bMask = 0xff;
356 }
357 else // transparency == Transparency_Alpha
358 {
359 alpha = InitAlpha(image, x, y);
360 }
361 }
362
363 switch ( transparency )
364 {
365 case Transparency_Alpha:
366 *alpha++ = a;
367 // fall through
368
369 case Transparency_None:
370 *ptrDst++ = g;
371 *ptrDst++ = g;
372 *ptrDst++ = g;
373 break;
374
375 case Transparency_Mask:
376 *ptrDst++ = rMask;
377 *ptrDst++ = bMask;
378 *ptrDst++ = gMask;
379 }
380 }
381 }
382 }
383 else // colour image: RGBRGB...
384 {
385 for ( png_uint_32 y = 0; y < height; y++ )
386 {
387 const unsigned char *ptrSrc = lines[y];
388 for ( png_uint_32 x = 0; x < width; x++ )
389 {
390 unsigned char r = *ptrSrc++;
391 unsigned char g = *ptrSrc++;
392 unsigned char b = *ptrSrc++;
393 unsigned char a = *ptrSrc++;
394
395 // the logic here is the same as for the grey case except
396 // where noted
397 if ( a != 0xff && transparency == Transparency_None )
398 {
399 transparency = CheckTransparency(ptrSrc, x, y,
400 width, height);
401
402 if ( transparency == Transparency_Mask )
403 {
404 FindMaskColour(lines, width, height,
405 rMask, gMask, bMask);
406 }
407 else // transparency == Transparency_Alpha
408 {
409 alpha = InitAlpha(image, x, y);
410 }
411
412 }
413
414 switch ( transparency )
415 {
416 case Transparency_Alpha:
417 *alpha++ = a;
418 // fall through
419
420 case Transparency_None:
421 *ptrDst++ = r;
422 *ptrDst++ = g;
423 *ptrDst++ = b;
424 break;
425
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 )
432 {
433 r++;
434 }
435
436 *ptrDst++ = rMask;
437 *ptrDst++ = bMask;
438 *ptrDst++ = gMask;
439 }
440 }
441 }
442 }
443
444 if ( transparency == Transparency_Mask )
445 {
446 image->SetMaskColour(rMask, gMask, bMask);
447 }
448 }
449
450 // temporarily disable the warning C4611 (interaction between '_setjmp' and
451 // C++ object destruction is non-portable) - I don't see any dtors here
452 #ifdef __VISUALC__
453 #pragma warning(disable:4611)
454 #endif /* VC++ */
455
456 bool
457 wxPNGHandler::LoadFile(wxImage *image,
458 wxInputStream& stream,
459 bool verbose,
460 int WXUNUSED(index))
461 {
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...)
464
465 unsigned char **lines = NULL;
466 png_infop info_ptr = (png_infop) NULL;
467 wxPNGInfoStruct wxinfo;
468
469 wxinfo.verbose = verbose;
470 wxinfo.stream.in = &stream;
471
472 image->Destroy();
473
474 png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING,
475 (voidp) NULL,
476 (png_error_ptr) NULL,
477 (png_error_ptr) NULL );
478 if (!png_ptr)
479 goto error;
480
481 png_set_error_fn(png_ptr, (png_voidp)NULL, wx_png_error, wx_png_warning);
482
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);
486
487 info_ptr = png_create_info_struct( png_ptr );
488 if (!info_ptr)
489 goto error;
490
491 if (setjmp(wxinfo.jmpbuf))
492 goto error;
493
494 png_uint_32 i, width, height;
495 int bit_depth, color_type, interlace_type;
496
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 );
499
500 if (color_type == PNG_COLOR_TYPE_PALETTE)
501 png_set_expand( png_ptr );
502
503 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
504 if (bit_depth < 8)
505 png_set_expand( png_ptr );
506
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 );
512
513 image->Create( (int)width, (int)height );
514
515 if (!image->Ok())
516 goto error;
517
518 lines = (unsigned char **)malloc( (size_t)(height * sizeof(unsigned char *)) );
519 if ( !lines )
520 goto error;
521
522 for (i = 0; i < height; i++)
523 {
524 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
525 {
526 for ( unsigned int n = 0; n < i; n++ )
527 free( lines[n] );
528 goto error;
529 }
530 }
531
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 );
535
536 // loaded successfully, now init wxImage with this data
537 CopyDataFromPNG(image, lines, width, height, color_type);
538
539 for ( i = 0; i < height; i++ )
540 free( lines[i] );
541 free( lines );
542
543 return TRUE;
544
545 error:
546 if (verbose)
547 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
548
549 if ( image->Ok() )
550 {
551 image->Destroy();
552 }
553
554 if ( lines )
555 {
556 free( lines );
557 }
558
559 if ( png_ptr )
560 {
561 if ( info_ptr )
562 {
563 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
564 free(info_ptr);
565 }
566 else
567 png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL );
568 }
569 return FALSE;
570 }
571
572 // ----------------------------------------------------------------------------
573 // writing PNGs
574 // ----------------------------------------------------------------------------
575
576 bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
577 {
578 wxPNGInfoStruct wxinfo;
579
580 wxinfo.verbose = verbose;
581 wxinfo.stream.out = &stream;
582
583 png_structp png_ptr = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
584 if (!png_ptr)
585 {
586 if (verbose)
587 wxLogError(_("Couldn't save PNG image."));
588 return FALSE;
589 }
590
591 png_set_error_fn(png_ptr, (png_voidp)NULL, wx_png_error, wx_png_warning);
592
593 png_infop info_ptr = png_create_info_struct(png_ptr);
594 if (info_ptr == NULL)
595 {
596 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
597 if (verbose)
598 wxLogError(_("Couldn't save PNG image."));
599 return FALSE;
600 }
601
602 if (setjmp(wxinfo.jmpbuf))
603 {
604 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
605 if (verbose)
606 wxLogError(_("Couldn't save PNG image."));
607 return FALSE;
608 }
609
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);
613
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);
617
618 png_color_8 sig_bit;
619 sig_bit.red = 8;
620 sig_bit.green = 8;
621 sig_bit.blue = 8;
622 sig_bit.alpha = 8;
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 );
627
628 unsigned char *data = (unsigned char *)malloc( image->GetWidth()*4 );
629 if (!data)
630 {
631 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
632 return FALSE;
633 }
634
635 for (int y = 0; y < image->GetHeight(); y++)
636 {
637 unsigned char *ptr = image->GetData() + (y * image->GetWidth() * 3);
638 for (int x = 0; x < image->GetWidth(); x++)
639 {
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()))
647 {
648 data[(x << 2) + 3] = 255;
649 }
650 else
651 {
652 data[(x << 2) + 3] = 0;
653 }
654 }
655 png_bytep row_ptr = data;
656 png_write_rows( png_ptr, &row_ptr, 1 );
657 }
658
659 free(data);
660 png_write_end( png_ptr, info_ptr );
661 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
662
663 return TRUE;
664 }
665
666 #ifdef __VISUALC__
667 #pragma warning(default:4611)
668 #endif /* VC++ */
669
670 #endif // wxUSE_STREAMS
671
672 #endif // wxUSE_LIBPNG