1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implements a PNG reader class + handler
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
13 # pragma implementation "pngread.h"
14 # pragma implementation "pnghand.h"
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
30 #if defined(__DARWIN__)
31 /* MW's math routines do certain things if __FP__ (the include guard around
32 CarbonCore's fp.h) is defined. CarbonCore's fp.h does certain things if
33 __cmath__ is defined so it seems the easy thing to do is to make sure
34 __cmath__ is effectively not defined which counteracts the MWERKS check
35 then when the real cmath is included everything will be okay.
37 #include <CoreServices/CoreServices.h>
39 #endif //defined(__DARWIN__)
50 #include "wx/msgdlg.h"
51 #include "wx/palette.h"
52 #include "wx/bitmap.h"
53 #include "wx/mac/pnghand.h"
54 #include "wx/mac/pngread.h"
55 #include "wx/mac/private.h"
61 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
62 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
64 extern CTabHandle
wxMacCreateColorTable( int numColors
) ;
65 extern void wxMacDestroyColorTable( CTabHandle colors
) ;
66 extern void wxMacSetColorTableEntry( CTabHandle newColors
, int index
, int red
, int green
, int blue
) ;
67 extern GWorldPtr
wxMacCreateGWorld( int width
, int height
, int depth
) ;
68 extern void wxMacDestroyGWorld( GWorldPtr gw
) ;
71 ima_png_error(png_struct
*png_ptr
, char *message
)
73 wxMessageBox(wxString::FromAscii(message
), wxT("PNG error"));
74 longjmp(png_ptr
->jmpbuf
, 1);
78 // static wxGifReaderIter* iter;
79 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
81 wxPNGReader::wxPNGReader(void)
84 RawImage
= NULL
; // Image data
86 Width
= 0; Height
= 0; // Dimensions
87 Depth
= 0; // (bits x pixel)
88 ColorType
= 0; // Bit 1 = Palette used
92 EfeWidth
= 0; // Efective Width
100 wxPNGReader::wxPNGReader ( char* ImageFileName
)
104 RawImage
= NULL
; // Image data
106 Width
= 0; Height
= 0; // Dimensions
107 Depth
= 0; // (bits x pixel)
108 ColorType
= 0; // Bit 1 = m_palette used
109 // Bit 2 = Color used
110 // Bit 3 = Alpha used
112 EfeWidth
= 0; // Efective Width
118 imageOK
= ReadFile (ImageFileName
);
122 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
124 Width
= width
; Height
= height
; Depth
= depth
;
125 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
132 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
134 lpbi
= wxMacCreateGWorld( Width
, Height
, Depth
);
137 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
138 int bitwidth
= width
;
139 if ( EfeWidth
> bitwidth
)
140 bitwidth
= EfeWidth
;
142 RawImage
= (byte
*) new char[ ( bitwidth
* Height
* ((Depth
+7)>>3) ) ];
147 wxPNGReader::~wxPNGReader ( )
149 if (RawImage
!= NULL
) {
154 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
157 if (m_palette
!= NULL
) {
164 int wxPNGReader::GetIndex(int x
, int y
)
166 if (!Inside(x
, y
) || (Depth
>8)) return -1;
168 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
169 int index
= (int)(*ImagePointer
);
173 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
175 if (!Inside(x
, y
)) return FALSE
;
178 return m_palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
179 /* PALETTEENTRY entry;
180 ::GetPaletteEntries((HPALETTE) m_palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
183 *b = entry.peBlue; */
185 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
186 *b
= ImagePointer
[0];
187 *g
= ImagePointer
[1];
188 *r
= ImagePointer
[2];
194 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
196 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
198 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
199 *ImagePointer
= index
;
204 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
206 if (!Inside(x
, y
)) return FALSE
;
208 if (ColorType
& COLORTYPE_PALETTE
)
210 if (!m_palette
) return FALSE
;
211 SetIndex(x
, y
, m_palette
->GetPixel(r
, g
, b
));
214 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
223 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
228 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
229 m_palette
= new wxPalette( *colourmap
);
231 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
235 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
238 m_palette
= new wxPalette();
244 m_palette
->Create(n
, r
, g
, b
);
245 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
247 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
251 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
254 m_palette
= new wxPalette();
258 byte r
[256], g
[256], b
[256];
260 for(int i
=0; i
<n
; i
++)
262 r
[i
] = rgb_struct
[i
].red
;
263 g
[i
] = rgb_struct
[i
].green
;
264 b
[i
] = rgb_struct
[i
].blue
;
266 // Added by JACS copying from Andrew Davison's additions
267 // to GIF-reading code
268 // Make transparency colour black...
270 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
272 m_palette
->Create(n
, r
, g
, b
);
273 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
275 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
278 void wxPNGReader::NullData()
281 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
284 if (m_palette
!= NULL
) {
290 wxBitmap
* wxPNGReader::GetBitmap(void)
292 wxBitmap
*bitmap
= new wxBitmap
;
293 if ( InstantiateBitmap(bitmap
) )
302 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
306 bitmap
->SetHBITMAP((WXHBITMAP
) lpbi
);
307 bitmap
->SetWidth(GetWidth());
308 bitmap
->SetHeight(GetHeight());
309 bitmap
->SetDepth(GetDepth());
310 if ( GetDepth() > 1 && m_palette
)
311 bitmap
->SetPalette(*m_palette
);
315 // Make a mask if appropriate
319 wxMask *mask = CreateMask();
320 bitmap->SetMask(mask);
323 lpbi
= NULL
; // bitmap has taken over ownership
331 HDC dc = ::CreateCompatibleDC(NULL);
335 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
336 // is a memory dc that must have a bitmap selected into it)
337 HDC dc2 = GetDC(NULL);
338 HBITMAP tmpBitmap = ::CreateCompatibleBitmap(dc2, GetWidth(), GetHeight());
339 ReleaseDC(NULL, dc2);
340 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, tmpBitmap);
344 HPALETTE oldPal = ::SelectPalette(dc, (HPALETTE) m_palette->GetHPALETTE(), FALSE);
345 ::RealizePalette(dc);
348 HBITMAP hBitmap = ::CreateDIBitmap(dc, lpbi,
349 CBM_INIT, RawImage, (LPBITMAPINFO) lpbi, DIB_PAL_COLORS);
351 ::SelectPalette(dc, NULL, TRUE);
352 ::SelectObject(dc, oldBitmap);
353 ::DeleteObject(tmpBitmap);
358 bitmap->SetHBITMAP((WXHBITMAP) hBitmap);
359 bitmap->SetWidth(GetWidth());
360 bitmap->SetHeight(GetHeight());
361 bitmap->SetDepth(GetDepth());
362 if ( GetDepth() > 1 && m_palette )
363 bitmap->SetPalette(*m_palette);
367 // Make a mask if appropriate
370 wxMask *mask = CreateMask();
371 bitmap->SetMask(mask);
388 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
390 wxPalette
*newCmap
= new wxPalette( *cmap
) ;
394 wxMask
*wxPNGReader::CreateMask(void)
397 HBITMAP hBitmap = ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL);
399 HDC dc = ::CreateCompatibleDC(NULL);
400 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, hBitmap);
402 int bgIndex = GetBGIndex();
406 for (x=0; x<GetWidth(); x++)
408 for (y=0; y<GetHeight(); y++)
410 int index = GetIndex(x, y);
411 if ( index == bgIndex )
412 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(0, 0, 0));
414 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(255, 255, 255));
418 ::SelectObject(dc, oldBitmap);
419 wxMask *mask = new wxMask;
420 mask->SetMaskBitmap((WXHBITMAP) hBitmap);
426 bool wxPNGReader::ReadFile(char * ImageFileName
)
431 strcpy(filename
, ImageFileName
);
436 wxPNGReaderIter
iter(this);
439 fp
= fopen( ImageFileName
, "rb" );
444 /* allocate the necessary structures */
445 png_ptr
= new (png_struct
);
452 info_ptr
= new (png_info
);
459 /* set error handling */
460 if (setjmp(png_ptr
->jmpbuf
))
462 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
467 /* If we get here, we had a problem reading the file */
470 //png_set_error(ima_png_error, NULL);
472 /* initialize the structures, info first for error handling */
473 png_info_init(info_ptr
);
474 png_read_init(png_ptr
);
476 /* set up the input control */
477 png_init_io(png_ptr
, fp
);
479 /* read the file information */
480 png_read_info(png_ptr
, info_ptr
);
482 /* allocate the memory to hold the image using the fields
484 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
486 if (info_ptr
->valid
& PNG_INFO_bKGD
)
488 png_set_background(png_ptr
, &(info_ptr
->background
),
489 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
490 if ( info_ptr
->num_palette
> 0 )
491 bgindex
= info_ptr
->background
.index
;
494 png_set_background(png_ptr
, &my_background
,
495 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
497 // Added by JACS: guesswork!
498 if ( info_ptr
->num_trans
!= 0 )
499 bgindex
= info_ptr
->num_trans
- 1 ;
502 /* tell libpng to strip 16 bit depth files down to 8 bits */
503 if (info_ptr
->bit_depth
== 16)
504 png_set_strip_16(png_ptr
);
506 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
507 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
508 info_ptr
->color_type
);
510 if (info_ptr
->num_palette
>0)
512 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
515 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
516 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
517 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
519 byte
*row_pointers
= new byte
[row_stride
];
521 /* turn on interlace handling */
522 if (info_ptr
->interlace_type
)
523 number_passes
= png_set_interlace_handling(png_ptr
);
526 // printf("NP = %d ", number_passes);
528 for (int pass
=0; pass
< number_passes
; pass
++)
533 GDHandle origDevice
;
535 GetGWorld( &origPort
, &origDevice
) ;
537 SetGWorld( (GWorldPtr
) lpbi
, NULL
) ;
540 // (unsigned char *)iter.GetRow();
541 if (info_ptr
->interlace_type
)
544 iter
.GetRow(row_pointers
, row_stride
);
545 png_read_row(png_ptr
, row_pointers
, NULL
);
548 png_read_row(png_ptr
, row_pointers
, NULL
);
550 if ( info_ptr
->palette
)
552 if ( pixel_depth
== 8 )
554 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
556 png_color_struct
* color
;
559 int index
= row_pointers
[i
] ;
560 color
= &info_ptr
->palette
[index
] ;
561 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
562 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
563 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
564 SetCPixel( i
, y
, &col
);
567 png_color_struct* color ;
569 unsigned char* p = &row_pointers[0] ;
573 color = &info_ptr->palette[index] ;
574 col.red = (color->red << 8) | color->red ;
575 col.green = (color->green << 8) | color->green ;
576 col.blue = (color->blue << 8) | color->blue ;
577 RGBForeColor( &col ) ;
578 col.red = col.green = col.blue = 0xFFFF ;
579 RGBBackColor( &col ) ;
580 for ( int i = 0 ; i < info_ptr->width ; ++i , ++p)
586 color = &info_ptr->palette[index] ;
587 col.red = (((int)color->red) << 8) | ((int)color->red) ;
588 col.green = (((int)color->green) << 8) | ((int)color->green) ;
589 col.blue = (((int)color->blue) << 8) | ((int)color->blue) ;
590 RGBForeColor( &col ) ;
593 LineTo( info_ptr->width , y ) ;
598 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
600 png_color_struct
* color
;
603 int byte
= ( i
* pixel_depth
) / 8 ;
604 int offset
= ( 8 - pixel_depth
) - ( i
* pixel_depth
) % 8 ;
606 int index
= ( row_pointers
[byte
] >> offset
) & ( 0xFF >> ( 8 - pixel_depth
) );
607 color
= &info_ptr
->palette
[index
] ;
608 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
609 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
610 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
611 SetCPixel( i
, y
, &col
);
617 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
619 png_color_struct
* color
;
621 color
=(png_color_struct
*) (&row_pointers
[i
*3]) ;
622 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
623 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
624 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
625 SetCPixel( i
, y
, &col
);
629 iter
.SetRow(row_pointers
, row_stride
);
632 while(iter
.PrevRow());
633 SetGWorld( origPort
, origDevice
) ;
635 // printf("Y=%d ",y);
637 delete[] row_pointers
;
639 /* read the rest of the file, getting any additional chunks
641 png_read_end(png_ptr
, info_ptr
);
643 /* clean up after the read, and free any memory allocated */
644 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
646 /* free the structures */
658 /* write a png file */
660 bool wxPNGReader::SaveFile(char * ImageFileName
)
663 strcpy(filename
, ImageFileName
);
665 wxPNGReaderIter
iter(this);
671 fp
= fopen(filename
, "wb");
675 /* allocate the necessary structures */
676 png_ptr
= new (png_struct
);
683 info_ptr
= new (png_info
);
691 /* set error handling */
692 if (setjmp(png_ptr
->jmpbuf
))
694 png_write_destroy(png_ptr
);
699 /* If we get here, we had a problem reading the file */
702 //png_set_error(ima_png_error, NULL);
704 // printf("writig pg %s ", filename);
705 /* initialize the structures */
706 png_info_init(info_ptr
);
707 png_write_init(png_ptr
);
709 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
710 /* set up the output control */
711 png_init_io(png_ptr
, fp
);
713 /* set the file information here */
714 info_ptr
->width
= GetWidth();
715 info_ptr
->height
= GetHeight();
716 info_ptr
->pixel_depth
= GetDepth();
717 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
718 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
719 info_ptr
->color_type
= GetColorType();
720 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
722 info_ptr
->rowbytes
= row_stride
;
725 // printf("P = %d D = %d RS= %d GD= %d CH= %d ", info_ptr->pixel_depth, info_ptr->bit_depth, row_stride, GetDepth(), info_ptr->channels);
726 /* set the palette if there is one */
727 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
729 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
730 info_ptr
->valid
|= PNG_INFO_PLTE
;
731 info_ptr
->palette
= new png_color
[256];
732 info_ptr
->num_palette
= 256;
733 for (int i
=0; i
<256; i
++)
734 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
736 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
739 /* optional significant bit chunk */
740 // info_ptr->valid |= PNG_INFO_sBIT;
741 // info_ptr->sig_bit = true_bit_depth;
743 /* optional gamma chunk */
744 // info_ptr->valid |= PNG_INFO_gAMA;
745 // info_ptr->gamma = gamma;
747 /* other optional chunks */
749 /* write the file information */
750 png_write_info(png_ptr
, info_ptr
);
752 /* set up the transformations you want. Note that these are
753 all optional. Only call them if you want them */
755 /* shift the pixels up to a legal bit depth and fill in
756 as appropriate to correctly scale the image */
757 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
759 /* pack pixels into bytes */
760 // png_set_packing(png_ptr);
762 /* flip bgr pixels to rgb */
763 // png_set_bgr(png_ptr);
765 /* swap bytes of 16 bit files to most significant bit first */
766 // png_set_swap(png_ptr);
768 /* get rid of filler bytes, pack rgb into 3 bytes */
769 // png_set_rgbx(png_ptr);
771 /* If you are only writing one row at a time, this works */
773 byte
*row_pointers
= new byte
[row_stride
];
776 // (unsigned char *)iter.GetRow();
777 iter
.GetRow(row_pointers
, row_stride
);
778 png_write_row(png_ptr
, row_pointers
);
779 } while(iter
.PrevRow());
781 delete[] row_pointers
;
783 /* write the rest of the file */
784 png_write_end(png_ptr
, info_ptr
);
786 /* clean up after the write, and free any memory allocated */
787 png_write_destroy(png_ptr
);
789 /* if you malloced the palette, free it here */
790 if (info_ptr
->palette
)
791 delete[] (info_ptr
->palette
);
793 /* free the structures */
804 static int Power(int x
, int y
)
808 for ( i
= 0; i
< y
; i
++)
815 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
816 'C', 'D', 'E', 'F' };
818 static void DecToHex(int dec
, char *buf
)
820 int firstDigit
= (int)(dec
/16.0);
821 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
822 buf
[0] = hexArray
[firstDigit
];
823 buf
[1] = hexArray
[secondDigit
];
828 bool wxPNGReader::SaveXPM(char *filename
, char *name
)
832 strcpy(nameStr
, name
);
835 wxString str
= wxString::FromAscii(filename
) ;
836 wxStripExtension( str
) ;
837 strcpy(nameStr
, str
.ToAscii() );
840 if ( GetDepth() > 4 )
842 // Only a depth of 4 and below allowed
849 wxSTD ofstream
str(filename
);
853 int noColours
= Power(2, GetDepth());
856 str
<< "/* XPM */\n";
857 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
858 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
861 int base
= 97 ; // start from 'a'
863 unsigned char red
, green
, blue
;
866 for ( i
= 0; i
< noColours
; i
++)
868 str
<< "\"" << (char)(base
+ i
) << " c #";
869 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
870 DecToHex(red
, hexBuf
);
872 DecToHex(green
, hexBuf
);
874 DecToHex(blue
, hexBuf
);
881 for ( y
= 0; y
< GetHeight(); y
++)
884 for ( x
= 0; x
< GetWidth(); x
++)
886 int index
= GetIndex(x
, y
);
887 str
<< (char)(base
+ index
) ;
899 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
901 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
902 int desiredWidth
, int desiredHeight
)
905 if (reader
.ReadFile( (char*)(const char*) name
.ToAscii() ) )
907 return reader
.InstantiateBitmap(bitmap
);
913 bool wxPNGFileHandler::SaveFile(const wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)
918 #endif //wxUSE_LIBPNG