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