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