1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implements a PNG reader class + handler
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
25 #if defined(__DARWIN__)
26 /* MW's math routines do certain things if __FP__ (the include guard around
27 CarbonCore's fp.h) is defined. CarbonCore's fp.h does certain things if
28 __cmath__ is defined so it seems the easy thing to do is to make sure
29 __cmath__ is effectively not defined which counteracts the MWERKS check
30 then when the real cmath is included everything will be okay.
32 #include <CoreServices/CoreServices.h>
34 #endif //defined(__DARWIN__)
45 #include "wx/msgdlg.h"
46 #include "wx/palette.h"
47 #include "wx/bitmap.h"
48 #include "wx/mac/pnghand.h"
49 #include "wx/mac/pngread.h"
50 #include "wx/mac/private.h"
56 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
57 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
59 extern CTabHandle
wxMacCreateColorTable( int numColors
) ;
60 extern void wxMacDestroyColorTable( CTabHandle colors
) ;
61 extern void wxMacSetColorTableEntry( CTabHandle newColors
, int index
, int red
, int green
, int blue
) ;
62 extern GWorldPtr
wxMacCreateGWorld( int width
, int height
, int depth
) ;
63 extern void wxMacDestroyGWorld( GWorldPtr gw
) ;
66 ima_png_error(png_struct
*png_ptr
, char *message
)
68 wxMessageBox(wxString::FromAscii(message
), wxT("PNG error"));
69 longjmp(png_ptr
->jmpbuf
, 1);
73 // static wxGifReaderIter* iter;
74 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
76 wxPNGReader::wxPNGReader(void)
79 RawImage
= NULL
; // Image data
81 Width
= 0; Height
= 0; // Dimensions
82 Depth
= 0; // (bits x pixel)
83 ColorType
= 0; // Bit 1 = Palette used
87 EfeWidth
= 0; // Efective Width
95 wxPNGReader::wxPNGReader ( char* ImageFileName
)
99 RawImage
= NULL
; // Image data
101 Width
= 0; Height
= 0; // Dimensions
102 Depth
= 0; // (bits x pixel)
103 ColorType
= 0; // Bit 1 = m_palette used
104 // Bit 2 = Color used
105 // Bit 3 = Alpha used
107 EfeWidth
= 0; // Efective Width
113 imageOK
= ReadFile (ImageFileName
);
117 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
119 Width
= width
; Height
= height
; Depth
= depth
;
120 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
127 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
129 lpbi
= wxMacCreateGWorld( Width
, Height
, Depth
);
132 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
133 int bitwidth
= width
;
134 if ( EfeWidth
> bitwidth
)
135 bitwidth
= EfeWidth
;
137 RawImage
= (byte
*) new char[ ( bitwidth
* Height
* ((Depth
+7)>>3) ) ];
142 wxPNGReader::~wxPNGReader ( )
144 if (RawImage
!= NULL
) {
149 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
152 if (m_palette
!= NULL
) {
159 int wxPNGReader::GetIndex(int x
, int y
)
161 if (!Inside(x
, y
) || (Depth
>8)) return -1;
163 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
164 int index
= (int)(*ImagePointer
);
168 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
170 if (!Inside(x
, y
)) return FALSE
;
173 return m_palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
174 /* PALETTEENTRY entry;
175 ::GetPaletteEntries((HPALETTE) m_palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
178 *b = entry.peBlue; */
180 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
181 *b
= ImagePointer
[0];
182 *g
= ImagePointer
[1];
183 *r
= ImagePointer
[2];
189 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
191 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
193 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
194 *ImagePointer
= index
;
199 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
201 if (!Inside(x
, y
)) return FALSE
;
203 if (ColorType
& COLORTYPE_PALETTE
)
205 if (!m_palette
) return FALSE
;
206 SetIndex(x
, y
, m_palette
->GetPixel(r
, g
, b
));
209 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
218 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
223 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
224 m_palette
= new wxPalette( *colourmap
);
226 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
230 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
233 m_palette
= new wxPalette();
239 m_palette
->Create(n
, r
, g
, b
);
240 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
242 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
246 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
249 m_palette
= new wxPalette();
253 byte r
[256], g
[256], b
[256];
255 for(int i
=0; i
<n
; i
++)
257 r
[i
] = rgb_struct
[i
].red
;
258 g
[i
] = rgb_struct
[i
].green
;
259 b
[i
] = rgb_struct
[i
].blue
;
261 // Added by JACS copying from Andrew Davison's additions
262 // to GIF-reading code
263 // Make transparency colour black...
265 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
267 m_palette
->Create(n
, r
, g
, b
);
268 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
270 // return (DibSetUsage(lpbi, (HPALETTE) m_palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
273 void wxPNGReader::NullData()
276 wxMacDestroyGWorld( (GWorldPtr
) lpbi
) ;
279 if (m_palette
!= NULL
) {
285 wxBitmap
* wxPNGReader::GetBitmap(void)
287 wxBitmap
*bitmap
= new wxBitmap
;
288 if ( InstantiateBitmap(bitmap
) )
297 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
301 bitmap
->SetHBITMAP((WXHBITMAP
) lpbi
);
302 bitmap
->SetWidth(GetWidth());
303 bitmap
->SetHeight(GetHeight());
304 bitmap
->SetDepth(GetDepth());
305 if ( GetDepth() > 1 && m_palette
)
306 bitmap
->SetPalette(*m_palette
);
310 // Make a mask if appropriate
314 wxMask *mask = CreateMask();
315 bitmap->SetMask(mask);
318 lpbi
= NULL
; // bitmap has taken over ownership
326 HDC dc = ::CreateCompatibleDC(NULL);
330 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
331 // is a memory dc that must have a bitmap selected into it)
332 HDC dc2 = GetDC(NULL);
333 HBITMAP tmpBitmap = ::CreateCompatibleBitmap(dc2, GetWidth(), GetHeight());
334 ReleaseDC(NULL, dc2);
335 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, tmpBitmap);
339 HPALETTE oldPal = ::SelectPalette(dc, (HPALETTE) m_palette->GetHPALETTE(), FALSE);
340 ::RealizePalette(dc);
343 HBITMAP hBitmap = ::CreateDIBitmap(dc, lpbi,
344 CBM_INIT, RawImage, (LPBITMAPINFO) lpbi, DIB_PAL_COLORS);
346 ::SelectPalette(dc, NULL, TRUE);
347 ::SelectObject(dc, oldBitmap);
348 ::DeleteObject(tmpBitmap);
353 bitmap->SetHBITMAP((WXHBITMAP) hBitmap);
354 bitmap->SetWidth(GetWidth());
355 bitmap->SetHeight(GetHeight());
356 bitmap->SetDepth(GetDepth());
357 if ( GetDepth() > 1 && m_palette )
358 bitmap->SetPalette(*m_palette);
362 // Make a mask if appropriate
365 wxMask *mask = CreateMask();
366 bitmap->SetMask(mask);
383 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
385 wxPalette
*newCmap
= new wxPalette( *cmap
) ;
389 wxMask
*wxPNGReader::CreateMask(void)
392 HBITMAP hBitmap = ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL);
394 HDC dc = ::CreateCompatibleDC(NULL);
395 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, hBitmap);
397 int bgIndex = GetBGIndex();
401 for (x=0; x<GetWidth(); x++)
403 for (y=0; y<GetHeight(); y++)
405 int index = GetIndex(x, y);
406 if ( index == bgIndex )
407 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(0, 0, 0));
409 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(255, 255, 255));
413 ::SelectObject(dc, oldBitmap);
414 wxMask *mask = new wxMask;
415 mask->SetMaskBitmap((WXHBITMAP) hBitmap);
421 bool wxPNGReader::ReadFile(char * ImageFileName
)
426 strcpy(filename
, ImageFileName
);
431 wxPNGReaderIter
iter(this);
434 fp
= fopen( ImageFileName
, "rb" );
439 /* allocate the necessary structures */
440 png_ptr
= new (png_struct
);
447 info_ptr
= new (png_info
);
454 /* set error handling */
455 if (setjmp(png_ptr
->jmpbuf
))
457 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
462 /* If we get here, we had a problem reading the file */
465 //png_set_error(ima_png_error, NULL);
467 /* initialize the structures, info first for error handling */
468 png_info_init(info_ptr
);
469 png_read_init(png_ptr
);
471 /* set up the input control */
472 png_init_io(png_ptr
, fp
);
474 /* read the file information */
475 png_read_info(png_ptr
, info_ptr
);
477 /* allocate the memory to hold the image using the fields
479 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
481 if (info_ptr
->valid
& PNG_INFO_bKGD
)
483 png_set_background(png_ptr
, &(info_ptr
->background
),
484 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
485 if ( info_ptr
->num_palette
> 0 )
486 bgindex
= info_ptr
->background
.index
;
489 png_set_background(png_ptr
, &my_background
,
490 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
492 // Added by JACS: guesswork!
493 if ( info_ptr
->num_trans
!= 0 )
494 bgindex
= info_ptr
->num_trans
- 1 ;
497 /* tell libpng to strip 16 bit depth files down to 8 bits */
498 if (info_ptr
->bit_depth
== 16)
499 png_set_strip_16(png_ptr
);
501 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
502 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
503 info_ptr
->color_type
);
505 if (info_ptr
->num_palette
>0)
507 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
510 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
511 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
512 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
514 byte
*row_pointers
= new byte
[row_stride
];
516 /* turn on interlace handling */
517 if (info_ptr
->interlace_type
)
518 number_passes
= png_set_interlace_handling(png_ptr
);
521 // printf("NP = %d ", number_passes);
523 for (int pass
=0; pass
< number_passes
; pass
++)
528 GDHandle origDevice
;
530 GetGWorld( &origPort
, &origDevice
) ;
532 SetGWorld( (GWorldPtr
) lpbi
, NULL
) ;
535 // (unsigned char *)iter.GetRow();
536 if (info_ptr
->interlace_type
)
539 iter
.GetRow(row_pointers
, row_stride
);
540 png_read_row(png_ptr
, row_pointers
, NULL
);
543 png_read_row(png_ptr
, row_pointers
, NULL
);
545 if ( info_ptr
->palette
)
547 if ( pixel_depth
== 8 )
549 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
551 png_color_struct
* color
;
554 int index
= row_pointers
[i
] ;
555 color
= &info_ptr
->palette
[index
] ;
556 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
557 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
558 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
559 SetCPixel( i
, y
, &col
);
562 png_color_struct* color ;
564 unsigned char* p = &row_pointers[0] ;
568 color = &info_ptr->palette[index] ;
569 col.red = (color->red << 8) | color->red ;
570 col.green = (color->green << 8) | color->green ;
571 col.blue = (color->blue << 8) | color->blue ;
572 RGBForeColor( &col ) ;
573 col.red = col.green = col.blue = 0xFFFF ;
574 RGBBackColor( &col ) ;
575 for ( int i = 0 ; i < info_ptr->width ; ++i , ++p)
581 color = &info_ptr->palette[index] ;
582 col.red = (((int)color->red) << 8) | ((int)color->red) ;
583 col.green = (((int)color->green) << 8) | ((int)color->green) ;
584 col.blue = (((int)color->blue) << 8) | ((int)color->blue) ;
585 RGBForeColor( &col ) ;
588 LineTo( info_ptr->width , y ) ;
593 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
595 png_color_struct
* color
;
598 int byte
= ( i
* pixel_depth
) / 8 ;
599 int offset
= ( 8 - pixel_depth
) - ( i
* pixel_depth
) % 8 ;
601 int index
= ( row_pointers
[byte
] >> offset
) & ( 0xFF >> ( 8 - pixel_depth
) );
602 color
= &info_ptr
->palette
[index
] ;
603 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
604 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
605 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
606 SetCPixel( i
, y
, &col
);
612 for ( size_t i
= 0 ; i
< info_ptr
->width
; ++i
)
614 png_color_struct
* color
;
616 color
=(png_color_struct
*) (&row_pointers
[i
*3]) ;
617 col
.red
= (((int)color
->red
) << 8) | ((int)color
->red
) ;
618 col
.green
= (((int)color
->green
) << 8) | ((int)color
->green
) ;
619 col
.blue
= (((int)color
->blue
) << 8) | ((int)color
->blue
) ;
620 SetCPixel( i
, y
, &col
);
624 iter
.SetRow(row_pointers
, row_stride
);
627 while(iter
.PrevRow());
628 SetGWorld( origPort
, origDevice
) ;
630 // printf("Y=%d ",y);
632 delete[] row_pointers
;
634 /* read the rest of the file, getting any additional chunks
636 png_read_end(png_ptr
, info_ptr
);
638 /* clean up after the read, and free any memory allocated */
639 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
641 /* free the structures */
653 /* write a png file */
655 bool wxPNGReader::SaveFile(char * ImageFileName
)
658 strcpy(filename
, ImageFileName
);
660 wxPNGReaderIter
iter(this);
666 fp
= fopen(filename
, "wb");
670 /* allocate the necessary structures */
671 png_ptr
= new (png_struct
);
678 info_ptr
= new (png_info
);
686 /* set error handling */
687 if (setjmp(png_ptr
->jmpbuf
))
689 png_write_destroy(png_ptr
);
694 /* If we get here, we had a problem reading the file */
697 //png_set_error(ima_png_error, NULL);
699 // printf("writig pg %s ", filename);
700 /* initialize the structures */
701 png_info_init(info_ptr
);
702 png_write_init(png_ptr
);
704 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
705 /* set up the output control */
706 png_init_io(png_ptr
, fp
);
708 /* set the file information here */
709 info_ptr
->width
= GetWidth();
710 info_ptr
->height
= GetHeight();
711 info_ptr
->pixel_depth
= GetDepth();
712 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
713 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
714 info_ptr
->color_type
= GetColorType();
715 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
717 info_ptr
->rowbytes
= row_stride
;
720 // 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);
721 /* set the palette if there is one */
722 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
724 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
725 info_ptr
->valid
|= PNG_INFO_PLTE
;
726 info_ptr
->palette
= new png_color
[256];
727 info_ptr
->num_palette
= 256;
728 for (int i
=0; i
<256; i
++)
729 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
731 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
734 /* optional significant bit chunk */
735 // info_ptr->valid |= PNG_INFO_sBIT;
736 // info_ptr->sig_bit = true_bit_depth;
738 /* optional gamma chunk */
739 // info_ptr->valid |= PNG_INFO_gAMA;
740 // info_ptr->gamma = gamma;
742 /* other optional chunks */
744 /* write the file information */
745 png_write_info(png_ptr
, info_ptr
);
747 /* set up the transformations you want. Note that these are
748 all optional. Only call them if you want them */
750 /* shift the pixels up to a legal bit depth and fill in
751 as appropriate to correctly scale the image */
752 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
754 /* pack pixels into bytes */
755 // png_set_packing(png_ptr);
757 /* flip bgr pixels to rgb */
758 // png_set_bgr(png_ptr);
760 /* swap bytes of 16 bit files to most significant bit first */
761 // png_set_swap(png_ptr);
763 /* get rid of filler bytes, pack rgb into 3 bytes */
764 // png_set_rgbx(png_ptr);
766 /* If you are only writing one row at a time, this works */
768 byte
*row_pointers
= new byte
[row_stride
];
771 // (unsigned char *)iter.GetRow();
772 iter
.GetRow(row_pointers
, row_stride
);
773 png_write_row(png_ptr
, row_pointers
);
774 } while(iter
.PrevRow());
776 delete[] row_pointers
;
778 /* write the rest of the file */
779 png_write_end(png_ptr
, info_ptr
);
781 /* clean up after the write, and free any memory allocated */
782 png_write_destroy(png_ptr
);
784 /* if you malloced the palette, free it here */
785 if (info_ptr
->palette
)
786 delete[] (info_ptr
->palette
);
788 /* free the structures */
799 static int Power(int x
, int y
)
803 for ( i
= 0; i
< y
; i
++)
810 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
811 'C', 'D', 'E', 'F' };
813 static void DecToHex(int dec
, char *buf
)
815 int firstDigit
= (int)(dec
/16.0);
816 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
817 buf
[0] = hexArray
[firstDigit
];
818 buf
[1] = hexArray
[secondDigit
];
823 bool wxPNGReader::SaveXPM(char *filename
, char *name
)
827 strcpy(nameStr
, name
);
830 wxString str
= wxString::FromAscii(filename
) ;
831 wxStripExtension( str
) ;
832 strcpy(nameStr
, str
.ToAscii() );
835 if ( GetDepth() > 4 )
837 // Only a depth of 4 and below allowed
844 wxSTD ofstream
str(filename
);
848 int noColours
= Power(2, GetDepth());
851 str
<< "/* XPM */\n";
852 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
853 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
856 int base
= 97 ; // start from 'a'
858 unsigned char red
, green
, blue
;
861 for ( i
= 0; i
< noColours
; i
++)
863 str
<< "\"" << (char)(base
+ i
) << " c #";
864 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
865 DecToHex(red
, hexBuf
);
867 DecToHex(green
, hexBuf
);
869 DecToHex(blue
, hexBuf
);
876 for ( y
= 0; y
< GetHeight(); y
++)
879 for ( x
= 0; x
< GetWidth(); x
++)
881 int index
= GetIndex(x
, y
);
882 str
<< (char)(base
+ index
) ;
894 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
896 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
897 int desiredWidth
, int desiredHeight
)
900 if (reader
.ReadFile( (char*)(const char*) name
.ToAscii() ) )
902 return reader
.InstantiateBitmap(bitmap
);
908 bool wxPNGFileHandler::SaveFile(const wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)
913 #endif //wxUSE_LIBPNG