]> git.saurik.com Git - wxWidgets.git/blame - src/common/imagpng.cpp
Store property name and value in wxPropertyGridEvent, keep track of live event instan...
[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
7d7b3f69
FM
151static void 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
7d7b3f69
FM
157static void 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
7d7b3f69 163static void
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 )
af588446 168 {
2b5f62a0 169 wxLogWarning( wxString::FromAscii(message) );
af588446 170 }
deb2fec0
SB
171}
172
ce615190
DS
173// from pngerror.c
174// so that the libpng doesn't send anything on stderr
7d7b3f69 175static void
0e0589e8 176PNGLINKAGEMODE wx_png_error(png_structp png_ptr, png_const_charp message)
ce615190 177{
ce615190 178 wx_png_warning(NULL, message);
0e0589e8
VZ
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);
ce615190
DS
184}
185
90350682
VZ
186} // extern "C"
187
27bb2b7c
VZ
188// ----------------------------------------------------------------------------
189// LoadFile() helpers
190// ----------------------------------------------------------------------------
191
d26d9754 192// determine the kind of transparency we need for this image: if the only alpha
c9fcf581
VZ
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
d26d9754
VZ
196//
197// parameters:
36308e0e 198// lines raw PNG data
d26d9754
VZ
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)
27bb2b7c 203Transparency
36308e0e 204CheckTransparency(unsigned char **lines,
d26d9754
VZ
205 png_uint_32 x, png_uint_32 y, png_uint_32 w, png_uint_32 h,
206 size_t numColBytes)
27bb2b7c 207{
d26d9754
VZ
208 // suppose that a mask will suffice and check all the remaining alpha
209 // values to see if it does
36308e0e 210 for ( ; y < h; y++ )
27bb2b7c 211 {
e45cc235
RD
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));
36308e0e 215
c9fcf581 216 for ( png_uint_32 x2 = x; x2 < w; x2++ )
27bb2b7c 217 {
c9fcf581 218 // skip the grey or colour byte(s)
36308e0e 219 ptr += numColBytes;
27bb2b7c 220
36308e0e 221 unsigned char a2 = *ptr++;
c9fcf581
VZ
222
223 if ( !IsTransparent(a2) && !IsOpaque(a2) )
27bb2b7c 224 {
d26d9754
VZ
225 // not fully opaque nor fully transparent, hence need alpha
226 return Transparency_Alpha;
27bb2b7c 227 }
27bb2b7c 228 }
c9fcf581
VZ
229
230 // during the next loop iteration check all the pixels in the row
231 x = 0;
27bb2b7c
VZ
232 }
233
d26d9754
VZ
234 // mask will be enough
235 return Transparency_Mask;
27bb2b7c
VZ
236}
237
238unsigned 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
c9fcf581
VZ
246 png_uint_32 end = y * image->GetWidth() + x;
247 for ( png_uint_32 i = 0; i < end; i++ )
27bb2b7c 248 {
c9fcf581
VZ
249 // all the previous pixels were opaque
250 *alpha++ = 0xff;
27bb2b7c
VZ
251 }
252
253 return alpha;
254}
255
256void
257FindMaskColour(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++;
dcc36b34 276 ++p; // jump over alpha
27bb2b7c
VZ
277
278 wxImageHistogramEntry&
279 entry = h[wxImageHistogram:: MakeKey(r2, g2, b2)];
280
281 if ( entry.value++ == 0 )
282 entry.index = nentries++;
283 }
284 }
285
f773e9b0 286 if ( !h.FindFirstUnusedColour(&rMask, &gMask, &bMask) )
27bb2b7c
VZ
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
303bool wxPNGHandler::DoCanRead( wxInputStream& stream )
304{
305 unsigned char hdr[4];
306
8faef7cc 307 if ( !stream.Read(hdr, WXSIZEOF(hdr)) ) // it's ok to modify the stream position here
7beb59f3 308 return false;
27bb2b7c
VZ
309
310 return memcmp(hdr, "\211PNG", WXSIZEOF(hdr)) == 0;
311}
312
313// convert data from RGB to wxImage format
314static
315void 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
c9fcf581 346 if ( !IsOpaque(a) && transparency == Transparency_None )
27bb2b7c
VZ
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
d26d9754
VZ
352 transparency = CheckTransparency
353 (
36308e0e 354 lines,
d26d9754
VZ
355 x, y,
356 width, height,
357 1
358 );
27bb2b7c
VZ
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 {
c9fcf581
VZ
378 case Transparency_Mask:
379 if ( IsTransparent(a) )
380 {
381 *ptrDst++ = rMask;
c9fcf581 382 *ptrDst++ = gMask;
dcc36b34 383 *ptrDst++ = bMask;
c9fcf581
VZ
384 break;
385 }
386 // else: !transparent
387
388 // must be opaque then as otherwise we shouldn't be
389 // using the mask at all
9a83f860 390 wxASSERT_MSG( IsOpaque(a), wxT("logic error") );
c9fcf581
VZ
391
392 // fall through
393
27bb2b7c 394 case Transparency_Alpha:
c9fcf581
VZ
395 if ( alpha )
396 *alpha++ = a;
27bb2b7c
VZ
397 // fall through
398
399 case Transparency_None:
400 *ptrDst++ = g;
401 *ptrDst++ = g;
402 *ptrDst++ = g;
403 break;
27bb2b7c
VZ
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
c9fcf581 422 if ( !IsOpaque(a) && transparency == Transparency_None )
27bb2b7c 423 {
d26d9754
VZ
424 transparency = CheckTransparency
425 (
36308e0e 426 lines,
d26d9754
VZ
427 x, y,
428 width, height,
429 3
430 );
27bb2b7c
VZ
431
432 if ( transparency == Transparency_Mask )
433 {
f773e9b0
RR
434 FindMaskColour(lines, width, height,
435 rMask, gMask, bMask);
27bb2b7c
VZ
436 }
437 else // transparency == Transparency_Alpha
438 {
439 alpha = InitAlpha(image, x, y);
440 }
441
442 }
443
444 switch ( transparency )
445 {
c9fcf581
VZ
446 case Transparency_Mask:
447 if ( IsTransparent(a) )
448 {
c9fcf581 449 *ptrDst++ = rMask;
c9fcf581 450 *ptrDst++ = gMask;
dcc36b34 451 *ptrDst++ = bMask;
c9fcf581
VZ
452 break;
453 }
999836aa
VZ
454 else // !transparent
455 {
456 // must be opaque then as otherwise we shouldn't be
457 // using the mask at all
9a83f860 458 wxASSERT_MSG( IsOpaque(a), wxT("logic error") );
999836aa
VZ
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 }
c9fcf581
VZ
470
471 // fall through
472
27bb2b7c 473 case Transparency_Alpha:
c9fcf581
VZ
474 if ( alpha )
475 *alpha++ = a;
27bb2b7c
VZ
476 // fall through
477
478 case Transparency_None:
479 *ptrDst++ = r;
480 *ptrDst++ = g;
481 *ptrDst++ = b;
482 break;
27bb2b7c
VZ
483 }
484 }
485 }
486 }
487
488 if ( transparency == Transparency_Mask )
489 {
490 image->SetMaskColour(rMask, gMask, bMask);
491 }
492}
493
3ca6a5f0
BP
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
27bb2b7c
VZ
500bool
501wxPNGHandler::LoadFile(wxImage *image,
502 wxInputStream& stream,
503 bool verbose,
504 int WXUNUSED(index))
e9c4b1a2 505{
7884ab90 506 // VZ: as this function uses setjmp() the only fool-proof error handling
e9c4b1a2 507 // method is to use goto (setjmp is not really C++ dtors friendly...)
717b9bf2 508
27bb2b7c
VZ
509 unsigned char **lines = NULL;
510 png_infop info_ptr = (png_infop) NULL;
bdffd806
VS
511 wxPNGInfoStruct wxinfo;
512
7884ab90
DS
513 png_uint_32 i, width, height = 0;
514 int bit_depth, color_type, interlace_type;
515
bdffd806
VS
516 wxinfo.verbose = verbose;
517 wxinfo.stream.in = &stream;
717b9bf2 518
e9c4b1a2 519 image->Destroy();
717b9bf2 520
d10c19d6
VZ
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 );
e9c4b1a2 528 if (!png_ptr)
27bb2b7c 529 goto error;
717b9bf2 530
bdffd806
VS
531 // NB: please see the comment near wxPNGInfoStruct declaration for
532 // explanation why this line is mandatory
e9b964cf 533 png_set_read_fn( png_ptr, &wxinfo, wx_PNG_stream_reader);
deb2fec0 534
e9c4b1a2
JS
535 info_ptr = png_create_info_struct( png_ptr );
536 if (!info_ptr)
27bb2b7c 537 goto error;
717b9bf2 538
bdffd806 539 if (setjmp(wxinfo.jmpbuf))
27bb2b7c 540 goto error;
717b9bf2 541
e9c4b1a2 542 png_read_info( png_ptr, info_ptr );
d3b9f782 543 png_get_IHDR( png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL );
717b9bf2 544
e9c4b1a2
JS
545 if (color_type == PNG_COLOR_TYPE_PALETTE)
546 png_set_expand( png_ptr );
717b9bf2 547
2b5f62a0
VZ
548 // Fix for Bug [ 439207 ] Monochrome PNG images come up black
549 if (bit_depth < 8)
550 png_set_expand( png_ptr );
551
e9c4b1a2
JS
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 );
717b9bf2 557
154e1ca1 558 image->Create((int)width, (int)height, (bool) false /* no need to init pixels */);
717b9bf2 559
e9c4b1a2 560 if (!image->Ok())
27bb2b7c 561 goto error;
717b9bf2 562
5550f66b
VZ
563 // initialize all line pointers to NULL to ensure that they can be safely
564 // free()d if an error occurs before all of them could be allocated
565 lines = (unsigned char **)calloc(height, sizeof(unsigned char *));
27bb2b7c
VZ
566 if ( !lines )
567 goto error;
717b9bf2 568
e9c4b1a2
JS
569 for (i = 0; i < height; i++)
570 {
479cd5de 571 if ((lines[i] = (unsigned char *)malloc( (size_t)(width * (sizeof(unsigned char) * 4)))) == NULL)
e9c4b1a2 572 goto error;
e9c4b1a2 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 612 if (verbose)
af588446 613 {
58c837a4 614 wxLogError(_("Couldn't load a PNG image - file is corrupted or not enough memory."));
af588446 615 }
717b9bf2 616
e9c4b1a2
JS
617 if ( image->Ok() )
618 {
619 image->Destroy();
620 }
717b9bf2 621
e9c4b1a2
JS
622 if ( lines )
623 {
0e0589e8
VZ
624 for ( unsigned int n = 0; n < height; n++ )
625 free( lines[n] );
626
e9c4b1a2
JS
627 free( lines );
628 }
717b9bf2 629
e9c4b1a2
JS
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 }
7beb59f3 640 return false;
e9c4b1a2
JS
641}
642
27bb2b7c
VZ
643// ----------------------------------------------------------------------------
644// writing PNGs
645// ----------------------------------------------------------------------------
646
deb2fec0 647bool wxPNGHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
e9c4b1a2 648{
bdffd806 649 wxPNGInfoStruct wxinfo;
717b9bf2 650
bdffd806
VS
651 wxinfo.verbose = verbose;
652 wxinfo.stream.out = &stream;
deb2fec0 653
d10c19d6
VZ
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 );
bdffd806
VS
661 if (!png_ptr)
662 {
663 if (verbose)
af588446 664 {
bdffd806 665 wxLogError(_("Couldn't save PNG image."));
af588446 666 }
7beb59f3 667 return false;
bdffd806 668 }
717b9bf2 669
bdffd806
VS
670 png_infop info_ptr = png_create_info_struct(png_ptr);
671 if (info_ptr == NULL)
672 {
673 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
674 if (verbose)
af588446 675 {
bdffd806 676 wxLogError(_("Couldn't save PNG image."));
af588446 677 }
7beb59f3 678 return false;
bdffd806 679 }
717b9bf2 680
bdffd806
VS
681 if (setjmp(wxinfo.jmpbuf))
682 {
683 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
684 if (verbose)
af588446 685 {
bdffd806 686 wxLogError(_("Couldn't save PNG image."));
af588446 687 }
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
a4efa721
VZ
702 bool bHasAlpha = image->HasAlpha();
703 bool bHasMask = image->HasMask();
704 bool bUseAlpha = bHasAlpha || bHasMask;
705
706 int iPngColorType;
707 if ( iColorType==wxPNG_TYPE_COLOUR )
708 {
709 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_RGB_ALPHA
710 : PNG_COLOR_TYPE_RGB;
711 }
712 else
713 {
714 iPngColorType = bUseAlpha ? PNG_COLOR_TYPE_GRAY_ALPHA
715 : PNG_COLOR_TYPE_GRAY;
716 }
bdffd806 717
d19ce8c4
FM
718 if (image->HasOption(wxIMAGE_OPTION_PNG_FILTER))
719 png_set_filter( png_ptr, PNG_FILTER_TYPE_BASE, image->GetOptionInt(wxIMAGE_OPTION_PNG_FILTER) );
720
721 if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL))
722 png_set_compression_level( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL) );
723
724 if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL))
725 png_set_compression_mem_level( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL) );
726
727 if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY))
728 png_set_compression_strategy( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY) );
729
730 if (image->HasOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE))
731 png_set_compression_buffer_size( png_ptr, image->GetOptionInt(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE) );
732
a4efa721
VZ
733 png_set_IHDR( png_ptr, info_ptr, image->GetWidth(), image->GetHeight(),
734 iBitDepth, iPngColorType,
735 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
736 PNG_FILTER_TYPE_BASE);
737
738 int iElements;
bdffd806 739 png_color_8 sig_bit;
a4efa721
VZ
740
741 if ( iPngColorType & PNG_COLOR_MASK_COLOR )
742 {
743 sig_bit.red =
744 sig_bit.green =
745 sig_bit.blue = (png_byte)iBitDepth;
746 iElements = 3;
747 }
748 else // grey
749 {
750 sig_bit.gray = (png_byte)iBitDepth;
751 iElements = 1;
752 }
753
754 if ( iPngColorType & PNG_COLOR_MASK_ALPHA )
755 {
756 sig_bit.alpha = (png_byte)iBitDepth;
757 iElements++;
758 }
759
dc683654
VZ
760 if ( iBitDepth == 16 )
761 iElements *= 2;
762
361f4288
VZ
763 // save the image resolution if we have it
764 int resX, resY;
765 switch ( GetResolutionFromOptions(*image, &resX, &resY) )
766 {
767 case wxIMAGE_RESOLUTION_INCHES:
095cb950
PC
768 {
769 const double INCHES_IN_METER = 10000.0 / 254;
770 resX = int(resX * INCHES_IN_METER);
771 resY = int(resY * INCHES_IN_METER);
772 }
361f4288
VZ
773 break;
774
775 case wxIMAGE_RESOLUTION_CM:
776 resX *= 100;
777 resY *= 100;
778 break;
779
780 case wxIMAGE_RESOLUTION_NONE:
781 break;
782
783 default:
9a83f860 784 wxFAIL_MSG( wxT("unsupported image resolution units") );
361f4288
VZ
785 }
786
787 if ( resX && resY )
788 png_set_pHYs( png_ptr, info_ptr, resX, resY, PNG_RESOLUTION_METER );
789
bdffd806
VS
790 png_set_sBIT( png_ptr, info_ptr, &sig_bit );
791 png_write_info( png_ptr, info_ptr );
792 png_set_shift( png_ptr, &sig_bit );
793 png_set_packing( png_ptr );
717b9bf2 794
a4efa721
VZ
795 unsigned char *
796 data = (unsigned char *)malloc( image->GetWidth() * iElements );
797 if ( !data )
bdffd806
VS
798 {
799 png_destroy_write_struct( &png_ptr, (png_infopp)NULL );
7beb59f3 800 return false;
bdffd806 801 }
717b9bf2 802
a4efa721
VZ
803 unsigned char *
804 pAlpha = (unsigned char *)(bHasAlpha ? image->GetAlpha() : NULL);
805 int iHeight = image->GetHeight();
806 int iWidth = image->GetWidth();
807
4c2740ec
WS
808 unsigned char uchMaskRed = 0, uchMaskGreen = 0, uchMaskBlue = 0;
809
810 if ( bHasMask )
811 {
812 uchMaskRed = image->GetMaskRed();
813 uchMaskGreen = image->GetMaskGreen();
814 uchMaskBlue = image->GetMaskBlue();
815 }
816
a4efa721
VZ
817 unsigned char *pColors = image->GetData();
818
819 for (int y = 0; y != iHeight; ++y)
bdffd806 820 {
a4efa721
VZ
821 unsigned char *pData = data;
822 for (int x = 0; x != iWidth; x++)
e9c4b1a2 823 {
a4efa721
VZ
824 unsigned char uchRed = *pColors++;
825 unsigned char uchGreen = *pColors++;
826 unsigned char uchBlue = *pColors++;
e1e36a3e 827
a4efa721 828 switch ( iColorType )
bdffd806 829 {
a4efa721 830 default:
9a83f860 831 wxFAIL_MSG( wxT("unknown wxPNG_TYPE_XXX") );
a4efa721
VZ
832 // fall through
833
834 case wxPNG_TYPE_COLOUR:
835 *pData++ = uchRed;
dc683654 836 if ( iBitDepth == 16 )
a4efa721
VZ
837 *pData++ = 0;
838 *pData++ = uchGreen;
dc683654 839 if ( iBitDepth == 16 )
a4efa721
VZ
840 *pData++ = 0;
841 *pData++ = uchBlue;
dc683654 842 if ( iBitDepth == 16 )
a4efa721
VZ
843 *pData++ = 0;
844 break;
845
846 case wxPNG_TYPE_GREY:
847 {
dc683654
VZ
848 // where do these coefficients come from? maybe we
849 // should have image options for them as well?
a4efa721
VZ
850 unsigned uiColor =
851 (unsigned) (76.544*(unsigned)uchRed +
852 150.272*(unsigned)uchGreen +
853 36.864*(unsigned)uchBlue);
dc683654
VZ
854
855 *pData++ = (unsigned char)((uiColor >> 8) & 0xFF);
856 if ( iBitDepth == 16 )
a4efa721 857 *pData++ = (unsigned char)(uiColor & 0xFF);
a4efa721
VZ
858 }
859 break;
860
861 case wxPNG_TYPE_GREY_RED:
862 *pData++ = uchRed;
dc683654 863 if ( iBitDepth == 16 )
a4efa721
VZ
864 *pData++ = 0;
865 break;
866 }
867
868 if ( bUseAlpha )
869 {
870 unsigned char uchAlpha = 255;
871 if ( bHasAlpha )
872 uchAlpha = *pAlpha++;
873
874 if ( bHasMask )
e1e36a3e 875 {
a4efa721
VZ
876 if ( (uchRed == uchMaskRed)
877 && (uchGreen == uchMaskGreen)
878 && (uchBlue == uchMaskBlue) )
879 uchAlpha = 0;
e1e36a3e 880 }
a4efa721
VZ
881
882 *pData++ = uchAlpha;
dc683654 883 if ( iBitDepth == 16 )
a4efa721 884 *pData++ = 0;
e9c4b1a2 885 }
e9c4b1a2 886 }
a4efa721 887
bdffd806
VS
888 png_bytep row_ptr = data;
889 png_write_rows( png_ptr, &row_ptr, 1 );
e9c4b1a2 890 }
bdffd806
VS
891
892 free(data);
893 png_write_end( png_ptr, info_ptr );
894 png_destroy_write_struct( &png_ptr, (png_infopp)&info_ptr );
895
7beb59f3 896 return true;
e9c4b1a2 897}
e9c4b1a2 898
3ca6a5f0
BP
899#ifdef __VISUALC__
900 #pragma warning(default:4611)
901#endif /* VC++ */
902
9ab6ee85 903#endif // wxUSE_STREAMS
e9c4b1a2 904
9ab6ee85 905#endif // wxUSE_LIBPNG