]> git.saurik.com Git - wxWidgets.git/blob - src/common/imagpng.cpp
updated wxExecute checks in wxGTK to be same as in other Unix ports after recent...
[wxWidgets.git] / src / common / imagpng.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/imagpng.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 // ----------------------------------------------------------------------------
15 // headers
16 // ----------------------------------------------------------------------------
17
18 // For compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
20
21 #ifdef __BORLANDC__
22 #pragma hdrstop
23 #endif
24
25 #if wxUSE_IMAGE && wxUSE_LIBPNG
26
27 #include "wx/imagpng.h"
28
29 #ifndef WX_PRECOMP
30 #include "wx/log.h"
31 #include "wx/app.h"
32 #include "wx/bitmap.h"
33 #include "wx/module.h"
34 #endif
35
36 #include "png.h"
37 #include "wx/filefn.h"
38 #include "wx/wfstream.h"
39 #include "wx/intl.h"
40 #include "wx/palette.h"
41
42 // For memcpy
43 #include <string.h>
44
45 // ----------------------------------------------------------------------------
46 // constants
47 // ----------------------------------------------------------------------------
48
49 // image can not have any transparent pixels at all, have only 100% opaque
50 // and/or 100% transparent pixels in which case a simple mask is enough to
51 // store this information in wxImage or have a real alpha channel in which case
52 // we need to have it in wxImage as well
53 enum Transparency
54 {
55 Transparency_None,
56 Transparency_Mask,
57 Transparency_Alpha
58 };
59
60 // ----------------------------------------------------------------------------
61 // local functions
62 // ----------------------------------------------------------------------------
63
64 // return the kind of transparency needed for this image assuming that it does
65 // have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
66 static Transparency
67 CheckTransparency(unsigned char **lines,
68 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
69 size_t numColBytes);
70
71 // init the alpha channel for the image and fill it with 1s up to (x, y)
72 static unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y);
73
74 // find a free colour for the mask in the PNG data array
75 static void
76 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
77 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask);
78
79 // is the pixel with this value of alpha a fully opaque one?
80 static inline
81 bool IsOpaque(unsigned char a)
82 {
83 return a == 0xff;
84 }
85
86 // is the pixel with this value of alpha a fully transparent one?
87 static inline
88 bool IsTransparent(unsigned char a)
89 {
90 return !a;
91 }
92
93 // ============================================================================
94 // wxPNGHandler implementation
95 // ============================================================================
96
97 IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler)
98
99 #if wxUSE_STREAMS
100
101 #ifndef PNGLINKAGEMODE
102 #ifdef __WATCOMC__
103 // we need an explicit cdecl for Watcom, at least according to
104 //
105 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
106 //
107 // more testing is needed for this however, please remove this comment
108 // if you can confirm that my fix works with Watcom 11
109 #define PNGLINKAGEMODE cdecl
110 #else
111 #define PNGLINKAGEMODE LINKAGEMODE
112 #endif
113 #endif
114
115
116 // VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
117 // First, let me describe what's the problem: libpng uses jmp_buf in
118 // its png_struct structure. Unfortunately, this structure is
119 // compiler-specific and may vary in size, so if you use libpng compiled
120 // as DLL with another compiler than the main executable, it may not work
121 // (this is for example the case with wxMGL port and SciTech MGL library
122 // that provides custom runtime-loadable libpng implementation with jmpbuf
123 // disabled altogether). Luckily, it is still possible to use setjmp() &
124 // longjmp() as long as the structure is not part of png_struct.
125 //
126 // Sadly, there's no clean way to attach user-defined data to png_struct.
127 // There is only one customizable place, png_struct.io_ptr, which is meant
128 // only for I/O routines and is set with png_set_read_fn or
129 // png_set_write_fn. The hacky part is that we use io_ptr to store
130 // a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
131
132 struct wxPNGInfoStruct
133 {
134 jmp_buf jmpbuf;
135 bool verbose;
136
137 union
138 {
139 wxInputStream *in;
140 wxOutputStream *out;
141 } stream;
142 };
143
144 #define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
145
146 // ----------------------------------------------------------------------------
147 // helper functions
148 // ----------------------------------------------------------------------------
149
150 extern "C"
151 {
152
153 void PNGLINKAGEMODE wx_PNG_stream_reader( png_structp png_ptr, png_bytep data,
154 png_size_t length )
155 {
156 WX_PNG_INFO(png_ptr)->stream.in->Read(data, length);
157 }
158
159 void PNGLINKAGEMODE wx_PNG_stream_writer( png_structp png_ptr, png_bytep data,
160 png_size_t length )
161 {
162 WX_PNG_INFO(png_ptr)->stream.out->Write(data, length);
163 }
164
165 void
166 PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message)
167 {
168 wxPNGInfoStruct *info = png_ptr ? WX_PNG_INFO(png_ptr) : NULL;
169 if ( !info || info->verbose )
170 wxLogWarning( wxString::FromAscii(message) );
171 }
172
173 // from pngerror.c
174 // so that the libpng doesn't send anything on stderr
175 void
176 PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message)
177 {
178 wx_png_warning(NULL, message);
179
180 // we're not using libpng built-in jump buffer (see comment before
181 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
182 // would just abort
183 longjmp(WX_PNG_INFO(png_ptr)->jmpbuf, 1);
184 }
185
186 } // extern "C"
187
188 // ----------------------------------------------------------------------------
189 // LoadFile() helpers
190 // ----------------------------------------------------------------------------
191
192 // determine the kind of transparency we need for this image: if the only alpha
193 // values it has are 0 (transparent) and 0xff (opaque) then we can simply
194 // create a mask for it, we should be ok with a simple mask but otherwise we
195 // need a full blown alpha channel in wxImage
196 //
197 // parameters:
198 // lines raw PNG data
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)
203 Transparency
204 CheckTransparency(unsigned char **lines,
205 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
206 size_t numColBytes)
207 {
208 // suppose that a mask will suffice and check all the remaining alpha
209 // values to see if it does
210 for ( ; y < h; y++ )
211 {
212 // each pixel is numColBytes+1 bytes, offset into the current line by
213 // the current x position
214 unsigned const char *ptr = lines[y] + (x * (numColBytes + 1));
215
216 for ( png_uint_32 x2 = x; x2 < w; x2++ )
217 {
218 // skip the grey or colour byte(s)
219 ptr += numColBytes;
220
221 unsigned char a2 = *ptr++;
222
223 if ( !IsTransparent(a2) && !IsOpaque(a2) )
224 {
225 // not fully opaque nor fully transparent, hence need alpha
226 return Transparency_Alpha;
227 }
228 }
229
230 // during the next loop iteration check all the pixels in the row
231 x = 0;
232 }
233
234 // mask will be enough
235 return Transparency_Mask;
236 }
237
238 unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y)
239 {
240 // create alpha channel
241 image->SetAlpha();
242
243 unsigned char *alpha = image->GetAlpha();
244
245 // set alpha for the pixels we had so far
246 png_uint_32 end = y * image->GetWidth() + x;
247 for ( png_uint_32 i = 0; i < end; i++ )
248 {
249 // all the previous pixels were opaque
250 *alpha++ = 0xff;
251 }
252
253 return alpha;
254 }
255
256 void
257 FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
258 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask)
259 {
260 // choosing the colour for the mask is more
261 // difficult: we need to iterate over the entire
262 // image for this in order to choose an unused
263 // colour (this is not very efficient but what else
264 // can we do?)
265 wxImageHistogram h;
266 unsigned nentries = 0;
267 unsigned char r2, g2, b2;
268 for ( png_uint_32 y2 = 0; y2 < height; y2++ )
269 {
270 const unsigned char *p = lines[y2];
271 for ( png_uint_32 x2 = 0; x2 < width; x2++ )
272 {
273 r2 = *p++;
274 g2 = *p++;
275 b2 = *p++;
276 ++p; // jump over alpha
277
278 wxImageHistogramEntry&
279 entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)];
280
281 if ( entry.value++ == 0 )
282 entry.index = nentries++;
283 }
284 }
285
286 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
287 {
288 wxLogWarning(_("Too many colours in PNG, the image may be slightly blurred."));
289
290 // use a fixed mask colour and we'll fudge
291 // the real pixels with this colour (see
292 // below)
293 rMask = 0xfe;
294 gMask = 0;
295 bMask = 0xff;
296 }
297 }
298
299 // ----------------------------------------------------------------------------
300 // reading PNGs
301 // ----------------------------------------------------------------------------
302
303 bool wxPNGHandler::DoCanRead( wxInputStream& stream )
304 {
305 unsigned char hdr[4];
306
307 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
308 return false;
309
310 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
311 }
312
313 // convert data from RGB to wxImage format
314 static
315 void CopyDataFromPNG(wxImage *image,
316 unsigned char **lines,
317 png_uint_32 width,
318 png_uint_32 height,
319 int color_type)
320 {
321 Transparency transparency = Transparency_None;
322
323 // only non NULL if transparency == Transparency_Alpha
324 unsigned char *alpha = NULL;
325
326 // RGB of the mask colour if transparency == Transparency_Mask
327 // (but init them anyhow to avoid compiler warnings)
328 unsigned char rMask = 0,
329 gMask = 0,
330 bMask = 0;
331
332 unsigned char *ptrDst = image->GetData();
333 if ( !(color_type & PNG_COLOR_MASK_COLOR) )
334 {
335 // grey image: GAGAGA... where G == grey component and A == alpha
336 for ( png_uint_32 y = 0; y < height; y++ )
337 {
338 const unsigned char *ptrSrc = lines[y];
339 for ( png_uint_32 x = 0; x < width; x++ )
340 {
341 unsigned char g = *ptrSrc++;
342 unsigned char a = *ptrSrc++;
343
344 // the first time we encounter a transparent pixel we must
345 // decide about what to do about them
346 if ( !IsOpaque(a) && transparency == Transparency_None )
347 {
348 // we'll need at least the mask for this image and
349 // maybe even full alpha channel info: the former is
350 // only enough if we have alpha values of 0 and 0xff
351 // only, otherwisewe need the latter
352 transparency = CheckTransparency
353 (
354 lines,
355 x, y,
356 width, height,
357 1
358 );
359
360 if ( transparency == Transparency_Mask )
361 {
362 // let's choose this colour for the mask: this is
363 // not a problem here as all the other pixels are
364 // grey, i.e. R == G == B which is not the case for
365 // this one so no confusion is possible
366 rMask = 0xff;
367 gMask = 0;
368 bMask = 0xff;
369 }
370 else // transparency == Transparency_Alpha
371 {
372 alpha = InitAlpha(image, x, y);
373 }
374 }
375
376 switch ( transparency )
377 {
378 case Transparency_Mask:
379 if ( IsTransparent(a) )
380 {
381 *ptrDst++ = rMask;
382 *ptrDst++ = gMask;
383 *ptrDst++ = bMask;
384 break;
385 }
386 // else: !transparent
387
388 // must be opaque then as otherwise we shouldn't be
389 // using the mask at all
390 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
391
392 // fall through
393
394 case Transparency_Alpha:
395 if ( alpha )
396 *alpha++ = a;
397 // fall through
398
399 case Transparency_None:
400 *ptrDst++ = g;
401 *ptrDst++ = g;
402 *ptrDst++ = g;
403 break;
404 }
405 }
406 }
407 }
408 else // colour image: RGBRGB...
409 {
410 for ( png_uint_32 y = 0; y < height; y++ )
411 {
412 const unsigned char *ptrSrc = lines[y];
413 for ( png_uint_32 x = 0; x < width; x++ )
414 {
415 unsigned char r = *ptrSrc++;
416 unsigned char g = *ptrSrc++;
417 unsigned char b = *ptrSrc++;
418 unsigned char a = *ptrSrc++;
419
420 // the logic here is the same as for the grey case except
421 // where noted
422 if ( !IsOpaque(a) && transparency == Transparency_None )
423 {
424 transparency = CheckTransparency
425 (
426 lines,
427 x, y,
428 width, height,
429 3
430 );
431
432 if ( transparency == Transparency_Mask )
433 {
434 FindMaskColour(lines, width, height,
435 rMask, gMask, bMask);
436 }
437 else // transparency == Transparency_Alpha
438 {
439 alpha = InitAlpha(image, x, y);
440 }
441
442 }
443
444 switch ( transparency )
445 {
446 case Transparency_Mask:
447 if ( IsTransparent(a) )
448 {
449 *ptrDst++ = rMask;
450 *ptrDst++ = gMask;
451 *ptrDst++ = bMask;
452 break;
453 }
454 else // !transparent
455 {
456 // must be opaque then as otherwise we shouldn't be
457 // using the mask at all
458 wxASSERT_MSG( IsOpaque(a), _T("logic error") );
459
460 // if we couldn't find a unique colour for the
461 // mask, we can have real pixels with the same
462 // value as the mask and it's better to slightly
463 // change their colour than to make them
464 // transparent
465 if ( r == rMask && g == gMask && b == bMask )
466 {
467 r++;
468 }
469 }
470
471 // fall through
472
473 case Transparency_Alpha:
474 if ( alpha )
475 *alpha++ = a;
476 // fall through
477
478 case Transparency_None:
479 *ptrDst++ = r;
480 *ptrDst++ = g;
481 *ptrDst++ = b;
482 break;
483 }
484 }
485 }
486 }
487
488 if ( transparency == Transparency_Mask )
489 {
490 image->SetMaskColour(rMask, gMask, bMask);
491 }
492 }
493
494 // temporarily disable the warning C4611 (interaction between '_setjmp' and
495 // C++ object destruction is non-portable) - I don't see any dtors here
496 #ifdef __VISUALC__
497 #pragma warning(disable:4611)
498 #endif /* VC++ */
499
500 bool
501 wxPNGHandler::LoadFile(wxImage *image,
502 wxInputStream& stream,
503 bool verbose,
504 int WXUNUSED(index))
505 {
506 // VZ: as this function uses setjmp() the only fool-proof error handling
507 // method is to use goto (setjmp is not really C++ dtors friendly...)
508
509 unsigned char **lines = NULL;
510 png_infop info_ptr = (png_infop) NULL;
511 wxPNGInfoStruct wxinfo;
512
513 png_uint_32 i, width, height = 0;
514 int bit_depth, color_type, interlace_type;
515
516 wxinfo.verbose = verbose;
517 wxinfo.stream.in = &stream;
518
519 image->Destroy();
520
521 png_structp png_ptr = png_create_read_struct
522 (
523 PNG_LIBPNG_VER_STRING,
524 (voidp) NULL,
525 wx_png_error,
526 wx_png_warning
527 );
528 if (!png_ptr)
529 goto error;
530
531 // NB: please see the comment near wxPNGInfoStruct declaration for
532 // explanation why this line is mandatory
533 png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader);
534
535 info_ptr = png_create_info_struct( png_ptr );
536 if (!info_ptr)
537 goto error;
538
539 if (setjmp(wxinfo.jmpbuf))
540 goto error;
541
542 png_read_info( png_ptr, info_ptr );
543 png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, (int*) NULL, (int*) NULL );
544
545 if (color_type == PNG_COLOR_TYPE_PALETTE)
546 png_set_expand( png_ptr );
547
548 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
549 if (bit_depth < 8)
550 png_set_expand( png_ptr );
551
552 png_set_strip_16( png_ptr );
553 png_set_packing( png_ptr );
554 if (png_get_valid( png_ptr, info_ptr, PNG_INFO_tRNS))
555 png_set_expand( png_ptr );
556 png_set_filler( png_ptr, 0xff, PNG_FILLER_AFTER );
557
558 image->Create((int)width, (int)height, (bool) false /* no need to init pixels */);
559
560 if (!image->Ok())
561 goto error;
562
563 lines = (unsigned char **)malloc( (size_t)(height * sizeof(unsigned char *)) );
564 if ( !lines )
565 goto error;
566
567 for (i = 0; i < height; i++)
568 {
569 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
570 {
571 for ( unsigned int n = 0; n < i; n++ )
572 free( lines[n] );
573 goto error;
574 }
575 }
576
577 png_read_image( png_ptr, lines );
578 png_read_end( png_ptr, info_ptr );
579
580 #if wxUSE_PALETTE
581 if (color_type == PNG_COLOR_TYPE_PALETTE)
582 {
583 const size_t ncolors = info_ptr->num_palette;
584 unsigned char* r = new unsigned char[ncolors];
585 unsigned char* g = new unsigned char[ncolors];
586 unsigned char* b = new unsigned char[ncolors];
587
588 for (size_t j = 0; j < ncolors; j++)
589 {
590 r[j] = info_ptr->palette[j].red;
591 g[j] = info_ptr->palette[j].green;
592 b[j] = info_ptr->palette[j].blue;
593 }
594
595 image->SetPalette(wxPalette(ncolors, r, g, b));
596 delete[] r;
597 delete[] g;
598 delete[] b;
599 }
600 #endif // wxUSE_PALETTE
601
602 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
603
604 // loaded successfully, now init wxImage with this data
605 CopyDataFromPNG(image, lines, width, height, color_type);
606
607 for ( i = 0; i < height; i++ )
608 free( lines[i] );
609 free( lines );
610
611 return true;
612
613 error:
614 if (verbose)
615 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
616
617 if ( image->Ok() )
618 {
619 image->Destroy();
620 }
621
622 if ( lines )
623 {
624 for ( unsigned int n = 0; n < height; n++ )
625 free( lines[n] );
626
627 free( lines );
628 }
629
630 if ( png_ptr )
631 {
632 if ( info_ptr )
633 {
634 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
635 free(info_ptr);
636 }
637 else
638 png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL );
639 }
640 return false;
641 }
642
643 // ----------------------------------------------------------------------------
644 // writing PNGs
645 // ----------------------------------------------------------------------------
646
647 bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
648 {
649 wxPNGInfoStruct wxinfo;
650
651 wxinfo.verbose = verbose;
652 wxinfo.stream.out = &stream;
653
654 png_structp png_ptr = png_create_write_struct
655 (
656 PNG_LIBPNG_VER_STRING,
657 NULL,
658 wx_png_error,
659 wx_png_warning
660 );
661 if (!png_ptr)
662 {
663 if (verbose)
664 wxLogError(_("Couldn't save PNG image."));
665 return false;
666 }
667
668 png_infop info_ptr = png_create_info_struct(png_ptr);
669 if (info_ptr == NULL)
670 {
671 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
672 if (verbose)
673 wxLogError(_("Couldn't save PNG image."));
674 return false;
675 }
676
677 if (setjmp(wxinfo.jmpbuf))
678 {
679 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
680 if (verbose)
681 wxLogError(_("Couldn't save PNG image."));
682 return false;
683 }
684
685 // NB: please see the comment near wxPNGInfoStruct declaration for
686 // explanation why this line is mandatory
687 png_set_write_fn( png_ptr, &wxinfo, wx_PNG_stream_writer, NULL);
688
689 const int iColorType = image->HasOption(wxIMAGE_OPTION_PNG_FORMAT)
690 ? image->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT)
691 : wxPNG_TYPE_COLOUR;
692 const int iBitDepth = image->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH)
693 ? image->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH)
694 : 8;
695
696 wxASSERT_MSG( iBitDepth == 8 || iBitDepth == 16,
697 _T("PNG bit depth must be 8 or 16") );
698
699 bool bHasAlpha = image->HasAlpha();
700 bool bHasMask = image->HasMask();
701 bool bUseAlpha = bHasAlpha || bHasMask;
702
703 int iPngColorType;
704 if ( iColorType==wxPNG_TYPE_COLOUR )
705 {
706 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_RGB_ALPHA
707 : PNG_COLOR_TYPE_RGB;
708 }
709 else
710 {
711 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_GRAY_ALPHA
712 : PNG_COLOR_TYPE_GRAY;
713 }
714
715 png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(),
716 iBitDepth, iPngColorType,
717 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
718 PNG_FILTER_TYPE_BASE);
719
720 int iElements;
721 png_color_8 sig_bit;
722
723 if ( iPngColorType & PNG_COLOR_MASK_COLOR )
724 {
725 sig_bit.red =
726 sig_bit.green =
727 sig_bit.blue = (png_byte)iBitDepth;
728 iElements = 3;
729 }
730 else // grey
731 {
732 sig_bit.gray = (png_byte)iBitDepth;
733 iElements = 1;
734 }
735
736 if ( iPngColorType & PNG_COLOR_MASK_ALPHA )
737 {
738 sig_bit.alpha = (png_byte)iBitDepth;
739 iElements++;
740 }
741
742 if ( iBitDepth == 16 )
743 iElements *= 2;
744
745 // save the image resolution if we have it
746 int resX, resY;
747 switch ( GetResolutionFromOptions(*image, &resX, &resY) )
748 {
749 case wxIMAGE_RESOLUTION_INCHES:
750 {
751 const double INCHES_IN_METER = 10000.0 / 254;
752 resX = int(resX * INCHES_IN_METER);
753 resY = int(resY * INCHES_IN_METER);
754 }
755 break;
756
757 case wxIMAGE_RESOLUTION_CM:
758 resX *= 100;
759 resY *= 100;
760 break;
761
762 case wxIMAGE_RESOLUTION_NONE:
763 break;
764
765 default:
766 wxFAIL_MSG( _T("unsupported image resolution units") );
767 }
768
769 if ( resX && resY )
770 png_set_pHYs( png_ptr, info_ptr, resX, resY, PNG_RESOLUTION_METER );
771
772 png_set_sBIT( png_ptr, info_ptr, &sig_bit );
773 png_write_info( png_ptr, info_ptr );
774 png_set_shift( png_ptr, &sig_bit );
775 png_set_packing( png_ptr );
776
777 unsigned char *
778 data = (unsigned char *)malloc( image->GetWidth() * iElements );
779 if ( !data )
780 {
781 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
782 return false;
783 }
784
785 unsigned char *
786 pAlpha = (unsigned char *)(bHasAlpha ? image->GetAlpha() : NULL);
787 int iHeight = image->GetHeight();
788 int iWidth = image->GetWidth();
789
790 unsigned char uchMaskRed = 0, uchMaskGreen = 0, uchMaskBlue = 0;
791
792 if ( bHasMask )
793 {
794 uchMaskRed = image->GetMaskRed();
795 uchMaskGreen = image->GetMaskGreen();
796 uchMaskBlue = image->GetMaskBlue();
797 }
798
799 unsigned char *pColors = image->GetData();
800
801 for (int y = 0; y != iHeight; ++y)
802 {
803 unsigned char *pData = data;
804 for (int x = 0; x != iWidth; x++)
805 {
806 unsigned char uchRed = *pColors++;
807 unsigned char uchGreen = *pColors++;
808 unsigned char uchBlue = *pColors++;
809
810 switch ( iColorType )
811 {
812 default:
813 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
814 // fall through
815
816 case wxPNG_TYPE_COLOUR:
817 *pData++ = uchRed;
818 if ( iBitDepth == 16 )
819 *pData++ = 0;
820 *pData++ = uchGreen;
821 if ( iBitDepth == 16 )
822 *pData++ = 0;
823 *pData++ = uchBlue;
824 if ( iBitDepth == 16 )
825 *pData++ = 0;
826 break;
827
828 case wxPNG_TYPE_GREY:
829 {
830 // where do these coefficients come from? maybe we
831 // should have image options for them as well?
832 unsigned uiColor =
833 (unsigned) (76.544*(unsigned)uchRed +
834 150.272*(unsigned)uchGreen +
835 36.864*(unsigned)uchBlue);
836
837 *pData++ = (unsigned char)((uiColor >> 8) & 0xFF);
838 if ( iBitDepth == 16 )
839 *pData++ = (unsigned char)(uiColor & 0xFF);
840 }
841 break;
842
843 case wxPNG_TYPE_GREY_RED:
844 *pData++ = uchRed;
845 if ( iBitDepth == 16 )
846 *pData++ = 0;
847 break;
848 }
849
850 if ( bUseAlpha )
851 {
852 unsigned char uchAlpha = 255;
853 if ( bHasAlpha )
854 uchAlpha = *pAlpha++;
855
856 if ( bHasMask )
857 {
858 if ( (uchRed == uchMaskRed)
859 && (uchGreen == uchMaskGreen)
860 && (uchBlue == uchMaskBlue) )
861 uchAlpha = 0;
862 }
863
864 *pData++ = uchAlpha;
865 if ( iBitDepth == 16 )
866 *pData++ = 0;
867 }
868 }
869
870 png_bytep row_ptr = data;
871 png_write_rows( png_ptr, &row_ptr, 1 );
872 }
873
874 free(data);
875 png_write_end( png_ptr, info_ptr );
876 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
877
878 return true;
879 }
880
881 #ifdef __VISUALC__
882 #pragma warning(default:4611)
883 #endif /* VC++ */
884
885 #endif // wxUSE_STREAMS
886
887 #endif // wxUSE_LIBPNG