]> git.saurik.com Git - wxWidgets.git/blob - src/common/imagpng.cpp
Removed all duplicated and complicated #ifdefs for enabling Skip and Abort in progres...
[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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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(unsigned char **lines,
78 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
79 size_t numColBytes);
80
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);
83
84 // find a free colour for the mask in the PNG data array
85 static void
86 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
87 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask);
88
89 // is the pixel with this value of alpha a fully opaque one?
90 static inline
91 bool IsOpaque(unsigned char a)
92 {
93 return a == 0xff;
94 }
95
96 // is the pixel with this value of alpha a fully transparent one?
97 static inline
98 bool IsTransparent(unsigned char a)
99 {
100 return !a;
101 }
102
103 // ============================================================================
104 // wxPNGHandler implementation
105 // ============================================================================
106
107 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler)
108
109 #if wxUSE_STREAMS
110
111 #ifndef PNGLINKAGEMODE
112 #ifdef __WATCOMC__
113 // we need an explicit cdecl for Watcom, at least according to
114 //
115 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
116 //
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
120 #else
121 #define PNGLINKAGEMODE LINKAGEMODE
122 #endif
123 #endif
124
125
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.
135 //
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.
141
142 struct wxPNGInfoStruct
143 {
144 jmp_buf jmpbuf;
145 bool verbose;
146
147 union
148 {
149 wxInputStream *in;
150 wxOutputStream *out;
151 } stream;
152 };
153
154 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
155
156 // ----------------------------------------------------------------------------
157 // helper functions
158 // ----------------------------------------------------------------------------
159
160 extern "C"
161 {
162
163 void PNGLINKAGEMODE wx_PNG_stream_reader( png_structp png_ptr, png_bytep data,
164 png_size_t length )
165 {
166 WX_PNG_INFO(png_ptr)->stream.in->Read(data, length);
167 }
168
169 void PNGLINKAGEMODE wx_PNG_stream_writer( png_structp png_ptr, png_bytep data,
170 png_size_t length )
171 {
172 WX_PNG_INFO(png_ptr)->stream.out->Write(data, length);
173 }
174
175 // from pngerror.c
176 // so that the libpng doesn't send anything on stderr
177 void
178 PNGLINKAGEMODE wx_png_error(png_structp WXUNUSED(png_ptr), png_const_charp message)
179 {
180 wxLogFatalError( wxString::FromAscii(message) );
181 }
182
183 void
184 PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message)
185 {
186 wxPNGInfoStruct *info = png_ptr ? WX_PNG_INFO(png_ptr) : NULL;
187 if ( !info || info->verbose )
188 wxLogWarning( wxString::FromAscii(message) );
189 }
190
191 } // extern "C"
192
193 // ----------------------------------------------------------------------------
194 // LoadFile() helpers
195 // ----------------------------------------------------------------------------
196
197 // determine the kind of transparency we need for this image: if the only alpha
198 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
199 // create a mask for it, we should be ok with a simple mask but otherwise we
200 // need a full blown alpha channel in wxImage
201 //
202 // parameters:
203 // lines raw PNG data
204 // x, y starting position
205 // w, h size of the image
206 // numColBytes number of colour bytes (1 for grey scale, 3 for RGB)
207 // (NB: alpha always follows the colour bytes)
208 Transparency
209 CheckTransparency(unsigned char **lines,
210 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
211 size_t numColBytes)
212 {
213 // suppose that a mask will suffice and check all the remaining alpha
214 // values to see if it does
215 for ( ; y < h; y++ )
216 {
217 // each pixel is numColBytes+1 bytes, offset into the current line by
218 // the current x position
219 unsigned const char *ptr = lines[y] + (x * (numColBytes + 1));
220
221 for ( png_uint_32 x2 = x; x2 < w; x2++ )
222 {
223 // skip the grey or colour byte(s)
224 ptr += numColBytes;
225
226 unsigned char a2 = *ptr++;
227
228 if ( !IsTransparent(a2) && !IsOpaque(a2) )
229 {
230 // not fully opaque nor fully transparent, hence need alpha
231 return Transparency_Alpha;
232 }
233 }
234
235 // during the next loop iteration check all the pixels in the row
236 x = 0;
237 }
238
239 // mask will be enough
240 return Transparency_Mask;
241 }
242
243 unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y)
244 {
245 // create alpha channel
246 image->SetAlpha();
247
248 unsigned char *alpha = image->GetAlpha();
249
250 // set alpha for the pixels we had so far
251 png_uint_32 end = y * image->GetWidth() + x;
252 for ( png_uint_32 i = 0; i < end; i++ )
253 {
254 // all the previous pixels were opaque
255 *alpha++ = 0xff;
256 }
257
258 return alpha;
259 }
260
261 void
262 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
263 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask)
264 {
265 // choosing the colour for the mask is more
266 // difficult: we need to iterate over the entire
267 // image for this in order to choose an unused
268 // colour (this is not very efficient but what else
269 // can we do?)
270 wxImageHistogram h;
271 unsigned nentries = 0;
272 unsigned char r2, g2, b2;
273 for ( png_uint_32 y2 = 0; y2 < height; y2++ )
274 {
275 const unsigned char *p = lines[y2];
276 for ( png_uint_32 x2 = 0; x2 < width; x2++ )
277 {
278 r2 = *p++;
279 g2 = *p++;
280 b2 = *p++;
281
282 wxImageHistogramEntry&
283 entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)];
284
285 if ( entry.value++ == 0 )
286 entry.index = nentries++;
287 }
288 }
289
290 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
291 {
292 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
293
294 // use a fixed mask colour and we'll fudge
295 // the real pixels with this colour (see
296 // below)
297 rMask = 0xfe;
298 gMask = 0;
299 bMask = 0xff;
300 }
301 }
302
303 // ----------------------------------------------------------------------------
304 // reading PNGs
305 // ----------------------------------------------------------------------------
306
307 bool wxPNGHandler::DoCanRead( wxInputStream& stream )
308 {
309 unsigned char hdr[4];
310
311 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
312 return false;
313
314 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
315 }
316
317 // convert data from RGB to wxImage format
318 static
319 void CopyDataFromPNG(wxImage *image,
320 unsigned char **lines,
321 png_uint_32 width,
322 png_uint_32 height,
323 int color_type)
324 {
325 Transparency transparency = Transparency_None;
326
327 // only non NULL if transparency == Transparency_Alpha
328 unsigned char *alpha = NULL;
329
330 // RGB of the mask colour if transparency == Transparency_Mask
331 // (but init them anyhow to avoid compiler warnings)
332 unsigned char rMask = 0,
333 gMask = 0,
334 bMask = 0;
335
336 unsigned char *ptrDst = image->GetData();
337 if ( !(color_type & PNG_COLOR_MASK_COLOR) )
338 {
339 // grey image: GAGAGA... where G == grey component and A == alpha
340 for ( png_uint_32 y = 0; y < height; y++ )
341 {
342 const unsigned char *ptrSrc = lines[y];
343 for ( png_uint_32 x = 0; x < width; x++ )
344 {
345 unsigned char g = *ptrSrc++;
346 unsigned char a = *ptrSrc++;
347
348 // the first time we encounter a transparent pixel we must
349 // decide about what to do about them
350 if ( !IsOpaque(a) && transparency == Transparency_None )
351 {
352 // we'll need at least the mask for this image and
353 // maybe even full alpha channel info: the former is
354 // only enough if we have alpha values of 0 and 0xff
355 // only, otherwisewe need the latter
356 transparency = CheckTransparency
357 (
358 lines,
359 x, y,
360 width, height,
361 1
362 );
363
364 if ( transparency == Transparency_Mask )
365 {
366 // let's choose this colour for the mask: this is
367 // not a problem here as all the other pixels are
368 // grey, i.e. R == G == B which is not the case for
369 // this one so no confusion is possible
370 rMask = 0xff;
371 gMask = 0;
372 bMask = 0xff;
373 }
374 else // transparency == Transparency_Alpha
375 {
376 alpha = InitAlpha(image, x, y);
377 }
378 }
379
380 switch ( transparency )
381 {
382 case Transparency_Mask:
383 if ( IsTransparent(a) )
384 {
385 *ptrDst++ = rMask;
386 *ptrDst++ = bMask;
387 *ptrDst++ = gMask;
388 break;
389 }
390 // else: !transparent
391
392 // must be opaque then as otherwise we shouldn't be
393 // using the mask at all
394 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
395
396 // fall through
397
398 case Transparency_Alpha:
399 if ( alpha )
400 *alpha++ = a;
401 // fall through
402
403 case Transparency_None:
404 *ptrDst++ = g;
405 *ptrDst++ = g;
406 *ptrDst++ = g;
407 break;
408 }
409 }
410 }
411 }
412 else // colour image: RGBRGB...
413 {
414 for ( png_uint_32 y = 0; y < height; y++ )
415 {
416 const unsigned char *ptrSrc = lines[y];
417 for ( png_uint_32 x = 0; x < width; x++ )
418 {
419 unsigned char r = *ptrSrc++;
420 unsigned char g = *ptrSrc++;
421 unsigned char b = *ptrSrc++;
422 unsigned char a = *ptrSrc++;
423
424 // the logic here is the same as for the grey case except
425 // where noted
426 if ( !IsOpaque(a) && transparency == Transparency_None )
427 {
428 transparency = CheckTransparency
429 (
430 lines,
431 x, y,
432 width, height,
433 3
434 );
435
436 if ( transparency == Transparency_Mask )
437 {
438 FindMaskColour(lines, width, height,
439 rMask, gMask, bMask);
440 }
441 else // transparency == Transparency_Alpha
442 {
443 alpha = InitAlpha(image, x, y);
444 }
445
446 }
447
448 switch ( transparency )
449 {
450 case Transparency_Mask:
451 if ( IsTransparent(a) )
452 {
453 *ptrDst++ = rMask;
454 *ptrDst++ = bMask;
455 *ptrDst++ = gMask;
456 break;
457 }
458 else // !transparent
459 {
460 // must be opaque then as otherwise we shouldn't be
461 // using the mask at all
462 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
463
464 // if we couldn't find a unique colour for the
465 // mask, we can have real pixels with the same
466 // value as the mask and it's better to slightly
467 // change their colour than to make them
468 // transparent
469 if ( r == rMask && g == gMask && b == bMask )
470 {
471 r++;
472 }
473 }
474
475 // fall through
476
477 case Transparency_Alpha:
478 if ( alpha )
479 *alpha++ = a;
480 // fall through
481
482 case Transparency_None:
483 *ptrDst++ = r;
484 *ptrDst++ = g;
485 *ptrDst++ = b;
486 break;
487 }
488 }
489 }
490 }
491
492 if ( transparency == Transparency_Mask )
493 {
494 image->SetMaskColour(rMask, gMask, bMask);
495 }
496 }
497
498 // temporarily disable the warning C4611 (interaction between '_setjmp' and
499 // C++ object destruction is non-portable) - I don't see any dtors here
500 #ifdef __VISUALC__
501 #pragma warning(disable:4611)
502 #endif /* VC++ */
503
504 bool
505 wxPNGHandler::LoadFile(wxImage *image,
506 wxInputStream& stream,
507 bool verbose,
508 int WXUNUSED(index))
509 {
510 // VZ: as this function uses setjmp() the only fool proof error handling
511 // method is to use goto (setjmp is not really C++ dtors friendly...)
512
513 unsigned char **lines = NULL;
514 png_infop info_ptr = (png_infop) NULL;
515 wxPNGInfoStruct wxinfo;
516
517 wxinfo.verbose = verbose;
518 wxinfo.stream.in = &stream;
519
520 image->Destroy();
521
522 png_structp png_ptr = png_create_read_struct
523 (
524 PNG_LIBPNG_VER_STRING,
525 (voidp) NULL,
526 wx_png_error,
527 wx_png_warning
528 );
529 if (!png_ptr)
530 goto error;
531
532 // NB: please see the comment near wxPNGInfoStruct declaration for
533 // explanation why this line is mandatory
534 png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader);
535
536 info_ptr = png_create_info_struct( png_ptr );
537 if (!info_ptr)
538 goto error;
539
540 if (setjmp(wxinfo.jmpbuf))
541 goto error;
542
543 png_uint_32 i, width, height;
544 int bit_depth, color_type, interlace_type;
545
546 png_read_info( png_ptr, info_ptr );
547 png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, (int*) NULL, (int*) NULL );
548
549 if (color_type == PNG_COLOR_TYPE_PALETTE)
550 png_set_expand( png_ptr );
551
552 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
553 if (bit_depth < 8)
554 png_set_expand( png_ptr );
555
556 png_set_strip_16( png_ptr );
557 png_set_packing( png_ptr );
558 if (png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS))
559 png_set_expand( png_ptr );
560 png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER );
561
562 image->Create((int)width, (int)height, (bool) false /* no need to init pixels */);
563
564 if (!image->Ok())
565 goto error;
566
567 lines = (unsigned char **)malloc( (size_t)(height * sizeof(unsigned char *)) );
568 if ( !lines )
569 goto error;
570
571 for (i = 0; i < height; i++)
572 {
573 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
574 {
575 for ( unsigned int n = 0; n < i; n++ )
576 free( lines[n] );
577 goto error;
578 }
579 }
580
581 png_read_image( png_ptr, lines );
582 png_read_end( png_ptr, info_ptr );
583 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
584
585 // loaded successfully, now init wxImage with this data
586 CopyDataFromPNG(image, lines, width, height, color_type);
587
588 for ( i = 0; i < height; i++ )
589 free( lines[i] );
590 free( lines );
591
592 return true;
593
594 error:
595 if (verbose)
596 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
597
598 if ( image->Ok() )
599 {
600 image->Destroy();
601 }
602
603 if ( lines )
604 {
605 free( lines );
606 }
607
608 if ( png_ptr )
609 {
610 if ( info_ptr )
611 {
612 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
613 free(info_ptr);
614 }
615 else
616 png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL );
617 }
618 return false;
619 }
620
621 // ----------------------------------------------------------------------------
622 // writing PNGs
623 // ----------------------------------------------------------------------------
624
625 bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
626 {
627 wxPNGInfoStruct wxinfo;
628
629 wxinfo.verbose = verbose;
630 wxinfo.stream.out = &stream;
631
632 png_structp png_ptr = png_create_write_struct
633 (
634 PNG_LIBPNG_VER_STRING,
635 NULL,
636 wx_png_error,
637 wx_png_warning
638 );
639 if (!png_ptr)
640 {
641 if (verbose)
642 wxLogError(_("Couldn't save PNG image."));
643 return false;
644 }
645
646 png_infop info_ptr = png_create_info_struct(png_ptr);
647 if (info_ptr == NULL)
648 {
649 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
650 if (verbose)
651 wxLogError(_("Couldn't save PNG image."));
652 return false;
653 }
654
655 if (setjmp(wxinfo.jmpbuf))
656 {
657 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
658 if (verbose)
659 wxLogError(_("Couldn't save PNG image."));
660 return false;
661 }
662
663 // NB: please see the comment near wxPNGInfoStruct declaration for
664 // explanation why this line is mandatory
665 png_set_write_fn( png_ptr, &wxinfo, wx_PNG_stream_writer, NULL);
666
667 png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(), 8,
668 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
669 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
670
671 png_color_8 sig_bit;
672 sig_bit.red = 8;
673 sig_bit.green = 8;
674 sig_bit.blue = 8;
675 sig_bit.alpha = 8;
676 png_set_sBIT( png_ptr, info_ptr, &sig_bit );
677 png_write_info( png_ptr, info_ptr );
678 png_set_shift( png_ptr, &sig_bit );
679 png_set_packing( png_ptr );
680
681 unsigned char *data = (unsigned char *)malloc( image->GetWidth()*4 );
682 if (!data)
683 {
684 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
685 return false;
686 }
687
688 for (int y = 0; y < image->GetHeight(); y++)
689 {
690 unsigned char *ptr = image->GetData() + (y * image->GetWidth() * 3);
691 for (int x = 0; x < image->GetWidth(); x++)
692 {
693 data[(x << 2) + 0] = *ptr++;
694 data[(x << 2) + 1] = *ptr++;
695 data[(x << 2) + 2] = *ptr++;
696 if ( image->HasAlpha() )
697 {
698 data[(x << 2) + 3] = image->GetAlpha(x, y);
699 }
700 else if (( !image->HasMask() ) || \
701 (data[(x << 2) + 0] != image->GetMaskRed()) || \
702 (data[(x << 2) + 1] != image->GetMaskGreen()) || \
703 (data[(x << 2) + 2] != image->GetMaskBlue()))
704 {
705 data[(x << 2) + 3] = 255;
706 }
707 else
708 {
709 data[(x << 2) + 3] = 0;
710 }
711 }
712 png_bytep row_ptr = data;
713 png_write_rows( png_ptr, &row_ptr, 1 );
714 }
715
716 free(data);
717 png_write_end( png_ptr, info_ptr );
718 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
719
720 return true;
721 }
722
723 #ifdef __VISUALC__
724 #pragma warning(default:4611)
725 #endif /* VC++ */
726
727 #endif // wxUSE_STREAMS
728
729 #endif // wxUSE_LIBPNG