]> git.saurik.com Git - wxWidgets.git/blame - src/common/imagpng.cpp
moved all wxDialog event handlers to wxDialogBase to avoid code duplication
[wxWidgets.git] / src / common / imagpng.cpp
CommitLineData
e9c4b1a2 1/////////////////////////////////////////////////////////////////////////////
27bb2b7c 2// Name: src/common/imagepng.cpp
e9c4b1a2
JS
3// Purpose: wxImage PNG handler
4// Author: Robert Roebling
5// RCS-ID: $Id$
6// Copyright: (c) Robert Roebling
65571936 7// Licence: wxWindows licence
e9c4b1a2
JS
8/////////////////////////////////////////////////////////////////////////////
9
27bb2b7c
VZ
10// ============================================================================
11// declarations
12// ============================================================================
13
27bb2b7c
VZ
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
e9c4b1a2
JS
18// For compilers that support precompilation, includes "wx.h".
19#include "wx/wxprec.h"
20
21#ifdef __BORLANDC__
8898456d 22 #pragma hdrstop
ce4169a4
RR
23#endif
24
8898456d
WS
25#if wxUSE_IMAGE && wxUSE_LIBPNG
26
0bca0373
WS
27#include "wx/imagpng.h"
28
ce4169a4 29#ifndef WX_PRECOMP
8898456d
WS
30 #include "wx/log.h"
31 #include "wx/app.h"
0bca0373 32 #include "wx/bitmap.h"
e9c4b1a2
JS
33#endif
34
ce4169a4 35#include "png.h"
e9c4b1a2
JS
36#include "wx/filefn.h"
37#include "wx/wfstream.h"
38#include "wx/intl.h"
39#include "wx/module.h"
40
41// For memcpy
42#include <string.h>
43
44#ifdef __SALFORDC__
45#ifdef FAR
46#undef FAR
47#endif
48#endif
49
27bb2b7c
VZ
50// ----------------------------------------------------------------------------
51// constants
52// ----------------------------------------------------------------------------
53
54// image can not have any transparent pixels at all, have only 100% opaque
55// and/or 100% transparent pixels in which case a simple mask is enough to
56// store this information in wxImage or have a real alpha channel in which case
57// we need to have it in wxImage as well
58enum Transparency
59{
60 Transparency_None,
61 Transparency_Mask,
62 Transparency_Alpha
63};
64
65// ----------------------------------------------------------------------------
66// local functions
67// ----------------------------------------------------------------------------
68
69// return the kind of transparency needed for this image assuming that it does
70// have transparent pixels, i.e. either Transparency_Alpha or Transparency_Mask
71static Transparency
36308e0e 72CheckTransparency(unsigned char **lines,
f7155274
VZ
73 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
74 size_t numColBytes);
27bb2b7c
VZ
75
76// init the alpha channel for the image and fill it with 1s up to (x, y)
77static unsigned char *InitAlpha(wxImage *image, png_uint_32 x, png_uint_32 y);
78
79// find a free colour for the mask in the PNG data array
80static void
81FindMaskColour(unsigned char **lines, png_uint_32 width, png_uint_32 height,
82 unsigned char& rMask, unsigned char& gMask, unsigned char& bMask);
e9c4b1a2 83
c9fcf581
VZ
84// is the pixel with this value of alpha a fully opaque one?
85static inline
86bool IsOpaque(unsigned char a)
87{
88 return a == 0xff;
89}
90
91// is the pixel with this value of alpha a fully transparent one?
92static inline
93bool IsTransparent(unsigned char a)
94{
95 return !a;
96}
97
27bb2b7c
VZ
98// ============================================================================
99// wxPNGHandler implementation
100// ============================================================================
e9c4b1a2 101
e9c4b1a2 102IMPLEMENT_DYNAMIC_CLASS(wxPNGHandler,wxImageHandler)
e9c4b1a2 103
e30285ab 104#if wxUSE_STREAMS
9ab6ee85 105
0729bd19 106#ifndef PNGLINKAGEMODE
fc038829 107 #if defined(__WATCOMC__) && ( defined(__WXMSW__) || defined(__WXMGL__) )
30e0e251
VZ
108 // we need an explicit cdecl for Watcom, at least according to
109 //
110 // http://sf.net/tracker/index.php?func=detail&aid=651492&group_id=9863&atid=109863
111 //
112 // more testing is needed for this however, please remove this comment
113 // if you can confirm that my fix works with Watcom 11
114 #define PNGLINKAGEMODE cdecl
115 #else
116 #define PNGLINKAGEMODE LINKAGEMODE
117 #endif
717b9bf2
DW
118#endif
119
bdffd806
VS
120
121// VS: wxPNGInfoStruct declared below is a hack that needs some explanation.
27bb2b7c
VZ
122// First, let me describe what's the problem: libpng uses jmp_buf in
123// its png_struct structure. Unfortunately, this structure is
124// compiler-specific and may vary in size, so if you use libpng compiled
bdffd806 125// as DLL with another compiler than the main executable, it may not work
27bb2b7c 126// (this is for example the case with wxMGL port and SciTech MGL library
bdffd806 127// that provides custom runtime-loadable libpng implementation with jmpbuf
27bb2b7c 128// disabled altogether). Luckily, it is still possible to use setjmp() &
bdffd806
VS
129// longjmp() as long as the structure is not part of png_struct.
130//
131// Sadly, there's no clean way to attach user-defined data to png_struct.
132// There is only one customizable place, png_struct.io_ptr, which is meant
27bb2b7c 133// only for I/O routines and is set with png_set_read_fn or
bdffd806
VS
134// png_set_write_fn. The hacky part is that we use io_ptr to store
135// a pointer to wxPNGInfoStruct that holds I/O structures _and_ jmp_buf.
136
137struct wxPNGInfoStruct
138{
139 jmp_buf jmpbuf;
140 bool verbose;
27bb2b7c 141
bdffd806
VS
142 union
143 {
144 wxInputStream *in;
145 wxOutputStream *out;
146 } stream;
147};
148
149#define WX_PNG_INFO(png_ptr) ((wxPNGInfoStruct*)png_get_io_ptr(png_ptr))
150
27bb2b7c
VZ
151// ----------------------------------------------------------------------------
152// helper functions
153// ----------------------------------------------------------------------------
bdffd806 154
90350682
VZ
155extern "C"
156{
157
e9b964cf
VS
158void PNGLINKAGEMODE wx_PNG_stream_reader( png_structp png_ptr, png_bytep data,
159 png_size_t length )
e9c4b1a2 160{
bdffd806 161 WX_PNG_INFO(png_ptr)->stream.in->Read(data, length);
e9c4b1a2
JS
162}
163
e9b964cf
VS
164void PNGLINKAGEMODE wx_PNG_stream_writer( png_structp png_ptr, png_bytep data,
165 png_size_t length )
e9c4b1a2 166{
bdffd806 167 WX_PNG_INFO(png_ptr)->stream.out->Write(data, length);
e9c4b1a2
JS
168}
169
deb2fec0 170void
bdffd806 171PNGLINKAGEMODE wx_png_warning(png_structp png_ptr, png_const_charp message)
deb2fec0 172{
d10c19d6
VZ
173 wxPNGInfoStruct *info = png_ptr ? WX_PNG_INFO(png_ptr) : NULL;
174 if ( !info || info->verbose )
2b5f62a0 175 wxLogWarning( wxString::FromAscii(message) );
deb2fec0
SB
176}
177
ce615190
DS
178// from pngerror.c
179// so that the libpng doesn't send anything on stderr
180void
0e0589e8 181PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message)
ce615190 182{
ce615190 183 wx_png_warning(NULL, message);
0e0589e8
VZ
184
185 // we're not using libpng built-in jump buffer (see comment before
186 // wxPNGInfoStruct above) so we have to return ourselves, otherwise libpng
187 // would just abort
188 longjmp(WX_PNG_INFO(png_ptr)->jmpbuf, 1);
ce615190
DS
189}
190
90350682
VZ
191} // extern "C"
192
27bb2b7c
VZ
193// ----------------------------------------------------------------------------
194// LoadFile() helpers
195// ----------------------------------------------------------------------------
196
d26d9754 197// determine the kind of transparency we need for this image: if the only alpha
c9fcf581
VZ
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
d26d9754
VZ
201//
202// parameters:
36308e0e 203// lines raw PNG data
d26d9754
VZ
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)
27bb2b7c 208Transparency
36308e0e 209CheckTransparency(unsigned char **lines,
d26d9754
VZ
210 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
211 size_t numColBytes)
27bb2b7c 212{
d26d9754
VZ
213 // suppose that a mask will suffice and check all the remaining alpha
214 // values to see if it does
36308e0e 215 for ( ; y < h; y++ )
27bb2b7c 216 {
e45cc235
RD
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));
36308e0e 220
c9fcf581 221 for ( png_uint_32 x2 = x; x2 < w; x2++ )
27bb2b7c 222 {
c9fcf581 223 // skip the grey or colour byte(s)
36308e0e 224 ptr += numColBytes;
27bb2b7c 225
36308e0e 226 unsigned char a2 = *ptr++;
c9fcf581
VZ
227
228 if ( !IsTransparent(a2) && !IsOpaque(a2) )
27bb2b7c 229 {
d26d9754
VZ
230 // not fully opaque nor fully transparent, hence need alpha
231 return Transparency_Alpha;
27bb2b7c 232 }
27bb2b7c 233 }
c9fcf581
VZ
234
235 // during the next loop iteration check all the pixels in the row
236 x = 0;
27bb2b7c
VZ
237 }
238
d26d9754
VZ
239 // mask will be enough
240 return Transparency_Mask;
27bb2b7c
VZ
241}
242
243unsigned 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
c9fcf581
VZ
251 png_uint_32 end = y * image->GetWidth() + x;
252 for ( png_uint_32 i = 0; i < end; i++ )
27bb2b7c 253 {
c9fcf581
VZ
254 // all the previous pixels were opaque
255 *alpha++ = 0xff;
27bb2b7c
VZ
256 }
257
258 return alpha;
259}
260
261void
262FindMaskColour(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
f773e9b0 290 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
27bb2b7c
VZ
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
307bool wxPNGHandler::DoCanRead( wxInputStream& stream )
308{
309 unsigned char hdr[4];
310
311 if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
7beb59f3 312 return false;
27bb2b7c
VZ
313
314 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
315}
316
317// convert data from RGB to wxImage format
318static
319void 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
c9fcf581 350 if ( !IsOpaque(a) && transparency == Transparency_None )
27bb2b7c
VZ
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
d26d9754
VZ
356 transparency = CheckTransparency
357 (
36308e0e 358 lines,
d26d9754
VZ
359 x, y,
360 width, height,
361 1
362 );
27bb2b7c
VZ
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 {
c9fcf581
VZ
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
27bb2b7c 398 case Transparency_Alpha:
c9fcf581
VZ
399 if ( alpha )
400 *alpha++ = a;
27bb2b7c
VZ
401 // fall through
402
403 case Transparency_None:
404 *ptrDst++ = g;
405 *ptrDst++ = g;
406 *ptrDst++ = g;
407 break;
27bb2b7c
VZ
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
c9fcf581 426 if ( !IsOpaque(a) && transparency == Transparency_None )
27bb2b7c 427 {
d26d9754
VZ
428 transparency = CheckTransparency
429 (
36308e0e 430 lines,
d26d9754
VZ
431 x, y,
432 width, height,
433 3
434 );
27bb2b7c
VZ
435
436 if ( transparency == Transparency_Mask )
437 {
f773e9b0
RR
438 FindMaskColour(lines, width, height,
439 rMask, gMask, bMask);
27bb2b7c
VZ
440 }
441 else // transparency == Transparency_Alpha
442 {
443 alpha = InitAlpha(image, x, y);
444 }
445
446 }
447
448 switch ( transparency )
449 {
c9fcf581
VZ
450 case Transparency_Mask:
451 if ( IsTransparent(a) )
452 {
c9fcf581
VZ
453 *ptrDst++ = rMask;
454 *ptrDst++ = bMask;
455 *ptrDst++ = gMask;
456 break;
457 }
999836aa
VZ
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 }
c9fcf581
VZ
474
475 // fall through
476
27bb2b7c 477 case Transparency_Alpha:
c9fcf581
VZ
478 if ( alpha )
479 *alpha++ = a;
27bb2b7c
VZ
480 // fall through
481
482 case Transparency_None:
483 *ptrDst++ = r;
484 *ptrDst++ = g;
485 *ptrDst++ = b;
486 break;
27bb2b7c
VZ
487 }
488 }
489 }
490 }
491
492 if ( transparency == Transparency_Mask )
493 {
494 image->SetMaskColour(rMask, gMask, bMask);
495 }
496}
497
3ca6a5f0
BP
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
27bb2b7c
VZ
504bool
505wxPNGHandler::LoadFile(wxImage *image,
506 wxInputStream& stream,
507 bool verbose,
508 int WXUNUSED(index))
e9c4b1a2 509{
7884ab90 510 // VZ: as this function uses setjmp() the only fool-proof error handling
e9c4b1a2 511 // method is to use goto (setjmp is not really C++ dtors friendly...)
717b9bf2 512
27bb2b7c
VZ
513 unsigned char **lines = NULL;
514 png_infop info_ptr = (png_infop) NULL;
bdffd806
VS
515 wxPNGInfoStruct wxinfo;
516
7884ab90
DS
517 png_uint_32 i, width, height = 0;
518 int bit_depth, color_type, interlace_type;
519
bdffd806
VS
520 wxinfo.verbose = verbose;
521 wxinfo.stream.in = &stream;
717b9bf2 522
e9c4b1a2 523 image->Destroy();
717b9bf2 524
d10c19d6
VZ
525 png_structp png_ptr = png_create_read_struct
526 (
527 PNG_LIBPNG_VER_STRING,
528 (voidp) NULL,
529 wx_png_error,
530 wx_png_warning
531 );
e9c4b1a2 532 if (!png_ptr)
27bb2b7c 533 goto error;
717b9bf2 534
bdffd806
VS
535 // NB: please see the comment near wxPNGInfoStruct declaration for
536 // explanation why this line is mandatory
e9b964cf 537 png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader);
deb2fec0 538
e9c4b1a2
JS
539 info_ptr = png_create_info_struct( png_ptr );
540 if (!info_ptr)
27bb2b7c 541 goto error;
717b9bf2 542
bdffd806 543 if (setjmp(wxinfo.jmpbuf))
27bb2b7c 544 goto error;
717b9bf2 545
e9c4b1a2
JS
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 );
717b9bf2 548
e9c4b1a2
JS
549 if (color_type == PNG_COLOR_TYPE_PALETTE)
550 png_set_expand( png_ptr );
717b9bf2 551
2b5f62a0
VZ
552 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
553 if (bit_depth < 8)
554 png_set_expand( png_ptr );
555
e9c4b1a2
JS
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 );
717b9bf2 561
154e1ca1 562 image->Create((int)width, (int)height, (bool) false /* no need to init pixels */);
717b9bf2 563
e9c4b1a2 564 if (!image->Ok())
27bb2b7c 565 goto error;
717b9bf2 566
479cd5de 567 lines = (unsigned char **)malloc( (size_t)(height * sizeof(unsigned char *)) );
27bb2b7c
VZ
568 if ( !lines )
569 goto error;
717b9bf2 570
e9c4b1a2
JS
571 for (i = 0; i < height; i++)
572 {
479cd5de 573 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
e9c4b1a2
JS
574 {
575 for ( unsigned int n = 0; n < i; n++ )
576 free( lines[n] );
577 goto error;
578 }
579 }
717b9bf2 580
27bb2b7c
VZ
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 );
717b9bf2 584
27bb2b7c
VZ
585 // loaded successfully, now init wxImage with this data
586 CopyDataFromPNG(image, lines, width, height, color_type);
717b9bf2 587
27bb2b7c
VZ
588 for ( i = 0; i < height; i++ )
589 free( lines[i] );
590 free( lines );
717b9bf2 591
7beb59f3 592 return true;
95ee0ac8 593
27bb2b7c 594error:
58c837a4
RR
595 if (verbose)
596 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
717b9bf2 597
e9c4b1a2
JS
598 if ( image->Ok() )
599 {
600 image->Destroy();
601 }
717b9bf2 602
e9c4b1a2
JS
603 if ( lines )
604 {
0e0589e8
VZ
605 for ( unsigned int n = 0; n < height; n++ )
606 free( lines[n] );
607
e9c4b1a2
JS
608 free( lines );
609 }
717b9bf2 610
e9c4b1a2
JS
611 if ( png_ptr )
612 {
613 if ( info_ptr )
614 {
615 png_destroy_read_struct( &png_ptr, &info_ptr, (png_infopp) NULL );
616 free(info_ptr);
617 }
618 else
619 png_destroy_read_struct( &png_ptr, (png_infopp) NULL, (png_infopp) NULL );
620 }
7beb59f3 621 return false;
e9c4b1a2
JS
622}
623
27bb2b7c
VZ
624// ----------------------------------------------------------------------------
625// writing PNGs
626// ----------------------------------------------------------------------------
627
deb2fec0 628bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
e9c4b1a2 629{
bdffd806 630 wxPNGInfoStruct wxinfo;
717b9bf2 631
bdffd806
VS
632 wxinfo.verbose = verbose;
633 wxinfo.stream.out = &stream;
deb2fec0 634
d10c19d6
VZ
635 png_structp png_ptr = png_create_write_struct
636 (
637 PNG_LIBPNG_VER_STRING,
638 NULL,
639 wx_png_error,
640 wx_png_warning
641 );
bdffd806
VS
642 if (!png_ptr)
643 {
644 if (verbose)
645 wxLogError(_("Couldn't save PNG image."));
7beb59f3 646 return false;
bdffd806 647 }
717b9bf2 648
bdffd806
VS
649 png_infop info_ptr = png_create_info_struct(png_ptr);
650 if (info_ptr == NULL)
651 {
652 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
653 if (verbose)
654 wxLogError(_("Couldn't save PNG image."));
7beb59f3 655 return false;
bdffd806 656 }
717b9bf2 657
bdffd806
VS
658 if (setjmp(wxinfo.jmpbuf))
659 {
660 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
661 if (verbose)
662 wxLogError(_("Couldn't save PNG image."));
7beb59f3 663 return false;
bdffd806 664 }
717b9bf2 665
bdffd806
VS
666 // NB: please see the comment near wxPNGInfoStruct declaration for
667 // explanation why this line is mandatory
e9b964cf 668 png_set_write_fn( png_ptr, &wxinfo, wx_PNG_stream_writer, NULL);
bdffd806 669
a4efa721
VZ
670 const int iColorType = image->HasOption(wxIMAGE_OPTION_PNG_FORMAT)
671 ? image->GetOptionInt(wxIMAGE_OPTION_PNG_FORMAT)
672 : wxPNG_TYPE_COLOUR;
673 const int iBitDepth = image->HasOption(wxIMAGE_OPTION_PNG_BITDEPTH)
674 ? image->GetOptionInt(wxIMAGE_OPTION_PNG_BITDEPTH)
675 : 8;
676
677 wxASSERT_MSG( iBitDepth == 8 || iBitDepth == 16,
678 _T("PNG bit depth must be 8 or 16") );
679
680 bool bHasAlpha = image->HasAlpha();
681 bool bHasMask = image->HasMask();
682 bool bUseAlpha = bHasAlpha || bHasMask;
683
684 int iPngColorType;
685 if ( iColorType==wxPNG_TYPE_COLOUR )
686 {
687 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_RGB_ALPHA
688 : PNG_COLOR_TYPE_RGB;
689 }
690 else
691 {
692 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_GRAY_ALPHA
693 : PNG_COLOR_TYPE_GRAY;
694 }
bdffd806 695
a4efa721
VZ
696 png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(),
697 iBitDepth, iPngColorType,
698 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
699 PNG_FILTER_TYPE_BASE);
700
701 int iElements;
bdffd806 702 png_color_8 sig_bit;
a4efa721
VZ
703
704 if ( iPngColorType & PNG_COLOR_MASK_COLOR )
705 {
706 sig_bit.red =
707 sig_bit.green =
708 sig_bit.blue = (png_byte)iBitDepth;
709 iElements = 3;
710 }
711 else // grey
712 {
713 sig_bit.gray = (png_byte)iBitDepth;
714 iElements = 1;
715 }
716
717 if ( iPngColorType & PNG_COLOR_MASK_ALPHA )
718 {
719 sig_bit.alpha = (png_byte)iBitDepth;
720 iElements++;
721 }
722
dc683654
VZ
723 if ( iBitDepth == 16 )
724 iElements *= 2;
725
bdffd806
VS
726 png_set_sBIT( png_ptr, info_ptr, &sig_bit );
727 png_write_info( png_ptr, info_ptr );
728 png_set_shift( png_ptr, &sig_bit );
729 png_set_packing( png_ptr );
717b9bf2 730
a4efa721
VZ
731 unsigned char *
732 data = (unsigned char *)malloc( image->GetWidth() * iElements );
733 if ( !data )
bdffd806
VS
734 {
735 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
7beb59f3 736 return false;
bdffd806 737 }
717b9bf2 738
a4efa721
VZ
739 unsigned char *
740 pAlpha = (unsigned char *)(bHasAlpha ? image->GetAlpha() : NULL);
741 int iHeight = image->GetHeight();
742 int iWidth = image->GetWidth();
743
4c2740ec
WS
744 unsigned char uchMaskRed = 0, uchMaskGreen = 0, uchMaskBlue = 0;
745
746 if ( bHasMask )
747 {
748 uchMaskRed = image->GetMaskRed();
749 uchMaskGreen = image->GetMaskGreen();
750 uchMaskBlue = image->GetMaskBlue();
751 }
752
a4efa721
VZ
753 unsigned char *pColors = image->GetData();
754
755 for (int y = 0; y != iHeight; ++y)
bdffd806 756 {
a4efa721
VZ
757 unsigned char *pData = data;
758 for (int x = 0; x != iWidth; x++)
e9c4b1a2 759 {
a4efa721
VZ
760 unsigned char uchRed = *pColors++;
761 unsigned char uchGreen = *pColors++;
762 unsigned char uchBlue = *pColors++;
e1e36a3e 763
a4efa721 764 switch ( iColorType )
bdffd806 765 {
a4efa721
VZ
766 default:
767 wxFAIL_MSG( _T("unknown wxPNG_TYPE_XXX") );
768 // fall through
769
770 case wxPNG_TYPE_COLOUR:
771 *pData++ = uchRed;
dc683654 772 if ( iBitDepth == 16 )
a4efa721
VZ
773 *pData++ = 0;
774 *pData++ = uchGreen;
dc683654 775 if ( iBitDepth == 16 )
a4efa721
VZ
776 *pData++ = 0;
777 *pData++ = uchBlue;
dc683654 778 if ( iBitDepth == 16 )
a4efa721
VZ
779 *pData++ = 0;
780 break;
781
782 case wxPNG_TYPE_GREY:
783 {
dc683654
VZ
784 // where do these coefficients come from? maybe we
785 // should have image options for them as well?
a4efa721
VZ
786 unsigned uiColor =
787 (unsigned) (76.544*(unsigned)uchRed +
788 150.272*(unsigned)uchGreen +
789 36.864*(unsigned)uchBlue);
dc683654
VZ
790
791 *pData++ = (unsigned char)((uiColor >> 8) & 0xFF);
792 if ( iBitDepth == 16 )
a4efa721 793 *pData++ = (unsigned char)(uiColor & 0xFF);
a4efa721
VZ
794 }
795 break;
796
797 case wxPNG_TYPE_GREY_RED:
798 *pData++ = uchRed;
dc683654 799 if ( iBitDepth == 16 )
a4efa721
VZ
800 *pData++ = 0;
801 break;
802 }
803
804 if ( bUseAlpha )
805 {
806 unsigned char uchAlpha = 255;
807 if ( bHasAlpha )
808 uchAlpha = *pAlpha++;
809
810 if ( bHasMask )
e1e36a3e 811 {
a4efa721
VZ
812 if ( (uchRed == uchMaskRed)
813 && (uchGreen == uchMaskGreen)
814 && (uchBlue == uchMaskBlue) )
815 uchAlpha = 0;
e1e36a3e 816 }
a4efa721
VZ
817
818 *pData++ = uchAlpha;
dc683654 819 if ( iBitDepth == 16 )
a4efa721 820 *pData++ = 0;
e9c4b1a2 821 }
e9c4b1a2 822 }
a4efa721 823
bdffd806
VS
824 png_bytep row_ptr = data;
825 png_write_rows( png_ptr, &row_ptr, 1 );
e9c4b1a2 826 }
bdffd806
VS
827
828 free(data);
829 png_write_end( png_ptr, info_ptr );
830 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
831
7beb59f3 832 return true;
e9c4b1a2 833}
e9c4b1a2 834
3ca6a5f0
BP
835#ifdef __VISUALC__
836 #pragma warning(default:4611)
837#endif /* VC++ */
838
9ab6ee85 839#endif // wxUSE_STREAMS
e9c4b1a2 840
9ab6ee85 841#endif // wxUSE_LIBPNG