1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implements a PNG reader class + handler
4 // Author: David Webster
8 // Copyright: (c) David Webster
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
29 #include "wx/palette.h"
30 #include "wx/bitmap.h"
32 #include "wx/msw/pngread.h"
33 #include "wx/msw/dibutils.h"
36 #include "../png/png.h"
39 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
40 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
42 #ifndef GlobalAllocPtr
43 #define GlobalPtrHandle(lp) \
44 ((HGLOBAL)GlobalHandle(lp))
46 #define GlobalLockPtr(lp) \
47 ((BOOL)GlobalLock(GlobalPtrHandle(lp)))
48 #define GlobalUnlockPtr(lp) \
49 GlobalUnlock(GlobalPtrHandle(lp))
51 #define GlobalAllocPtr(flags, cb) \
52 (GlobalLock(GlobalAlloc((flags), (cb))))
53 #define GlobalReAllocPtr(lp, cbNew, flags) \
54 (GlobalUnlockPtr(lp), GlobalLock(GlobalReAlloc(GlobalPtrHandle(lp) , (cbNew), (flags))))
55 #define GlobalFreePtr(lp) \
56 (GlobalUnlockPtr(lp), (BOOL)GlobalFree(GlobalPtrHandle(lp)))
61 ima_png_error(png_struct
*png_ptr
, char *message
)
63 // wxMessageBox(message, "PNG error");
65 longjmp(png_ptr
->jmpbuf
, 1);
69 // static wxGifReaderIter* iter;
70 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
72 wxPNGReader::wxPNGReader()
75 RawImage
= NULL
; // Image data
77 Width
= 0; Height
= 0; // Dimensions
78 Depth
= 0; // (bits x pixel)
79 ColorType
= 0; // Bit 1 = Palette used
83 EfeWidth
= 0; // Efective Width
91 wxPNGReader::wxPNGReader ( wxChar
* ImageFileName
)
95 RawImage
= NULL
; // Image data
97 Width
= 0; Height
= 0; // Dimensions
98 Depth
= 0; // (bits x pixel)
99 ColorType
= 0; // Bit 1 = Palette used
100 // Bit 2 = Color used
101 // Bit 3 = Alpha used
103 EfeWidth
= 0; // Efective Width
109 imageOK
= ReadFile (ImageFileName
);
113 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
115 Width
= width
; Height
= height
; Depth
= depth
;
116 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
120 GlobalFreePtr((unsigned int) lpbi
);
128 lpbi
= wxDibCreate(Depth
, Width
, Height
);
130 RawImage
= (ImagePointerType
)wxDibPtr(lpbi
);
131 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
136 wxPNGReader::~wxPNGReader ( )
140 GlobalFreePtr((unsigned int) lpbi
);
149 int wxPNGReader::GetIndex(int x
, int y
)
151 if (!Inside(x
, y
) || (Depth
>8)) return -1;
153 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
154 int index
= (int)(*ImagePointer
);
158 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
160 if (!Inside(x
, y
)) return FALSE
;
163 return Palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
164 /* PALETTEENTRY entry;
165 ::GetPaletteEntries((HPALETTE) Palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
168 *b = entry.peBlue; */
170 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
171 *b
= ImagePointer
[0];
172 *g
= ImagePointer
[1];
173 *r
= ImagePointer
[2];
179 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
181 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
183 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
184 *ImagePointer
= index
;
189 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
191 if (!Inside(x
, y
)) return FALSE
;
193 if (ColorType
& COLORTYPE_PALETTE
)
195 if (!Palette
) return FALSE
;
196 SetIndex(x
, y
, Palette
->GetPixel(r
, g
, b
));
199 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
208 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
212 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
214 return (wxDibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
218 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
220 Palette
= new wxPalette();
226 Palette
->Create(n
, r
, g
, b
);
227 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
228 return (wxDibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
232 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
234 Palette
= new wxPalette();
238 byte r
[256], g
[256], b
[256];
240 for(int i
=0; i
<n
; i
++)
242 r
[i
] = rgb_struct
[i
].red
;
243 g
[i
] = rgb_struct
[i
].green
;
244 b
[i
] = rgb_struct
[i
].blue
;
246 // Added by JACS copying from Andrew Davison's additions
247 // to GIF-reading code
248 // Make transparency colour black...
250 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
252 Palette
->Create(n
, r
, g
, b
);
253 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
254 return (wxDibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
257 void wxPNGReader::NullData()
263 wxBitmap
* wxPNGReader::GetBitmap()
265 wxBitmap
*bitmap
= new wxBitmap
;
266 if ( InstantiateBitmap(bitmap
) )
275 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
277 HDC dc
= ::CreateCompatibleDC(NULL
);
281 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
282 // is a memory dc that must have a bitmap selected into it)
283 HDC dc2
= GetDC(NULL
);
284 HBITMAP tmpBitmap
= ::CreateCompatibleBitmap(dc2
, GetWidth(), GetHeight());
285 ReleaseDC(NULL
, dc2
);
286 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, tmpBitmap
);
290 ::SelectPalette(dc
, (HPALETTE
) Palette
->GetHPALETTE(), FALSE
);
291 ::RealizePalette(dc
);
294 HBITMAP hBitmap
= ::CreateDIBitmap(dc
, lpbi
,
295 CBM_INIT
, RawImage
, (LPBITMAPINFO
) lpbi
, DIB_PAL_COLORS
);
297 ::SelectPalette(dc
, NULL
, TRUE
);
298 ::SelectObject(dc
, oldBitmap
);
299 ::DeleteObject(tmpBitmap
);
304 bitmap
->SetHBITMAP((WXHBITMAP
) hBitmap
);
305 bitmap
->SetWidth(GetWidth());
306 bitmap
->SetHeight(GetHeight());
307 bitmap
->SetDepth(GetDepth());
308 if ( GetDepth() > 1 && Palette
)
309 bitmap
->SetPalette(*Palette
);
313 // Make a mask if appropriate
316 wxMask
*mask
= CreateMask();
317 bitmap
->SetMask(mask
);
332 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
334 // To get number of entries...
336 ::GetObject((HPALETTE
) cmap
->GetHPALETTE(), sizeof(WORD
), &count
);
338 LOGPALETTE
* logPal
= (LOGPALETTE
*)
339 new BYTE
[sizeof(LOGPALETTE
) + count
*sizeof(PALETTEENTRY
)];
340 logPal
->palVersion
= 0x300;
341 logPal
->palNumEntries
= count
;
342 ::GetPaletteEntries((HPALETTE
) cmap
->GetHPALETTE(), 0, count
, logPal
->palPalEntry
);
344 HPALETTE hPalette
= ::CreatePalette(logPal
);
347 wxPalette
*newCmap
= new wxPalette
;
348 newCmap
->SetHPALETTE((WXHPALETTE
) hPalette
);
352 wxMask
*wxPNGReader::CreateMask()
354 HBITMAP hBitmap
= ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL
);
356 HDC dc
= ::CreateCompatibleDC(NULL
);
357 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, hBitmap
);
359 int bgIndex
= GetBGIndex();
363 for (x
=0; x
<GetWidth(); x
++)
365 for (y
=0; y
<GetHeight(); y
++)
367 int index
= GetIndex(x
, y
);
368 if ( index
== bgIndex
)
369 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(0, 0, 0));
371 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(255, 255, 255));
375 ::SelectObject(dc
, oldBitmap
);
376 wxMask
*mask
= new wxMask
;
377 mask
->SetMaskBitmap((WXHBITMAP
) hBitmap
);
381 bool wxPNGReader::ReadFile(wxChar
* ImageFileName
)
384 wxStrcpy(filename
, ImageFileName
);
387 FILE *fp
= fopen(wxConvFile
.cWX2MB(filename
), "rb");
391 /* allocate the necessary structures */
392 png_struct
*png_ptr
= new (png_struct
);
399 png_info
*info_ptr
= new (png_info
);
407 /* set error handling */
408 if (setjmp(png_ptr
->jmpbuf
))
410 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
415 /* If we get here, we had a problem reading the file */
418 //png_set_error(ima_png_error, NULL);
420 /* initialize the structures, info first for error handling */
421 png_info_init(info_ptr
);
422 png_read_init(png_ptr
);
424 /* set up the input control */
425 png_init_io(png_ptr
, fp
);
427 /* read the file information */
428 png_read_info(png_ptr
, info_ptr
);
430 /* allocate the memory to hold the image using the fields
432 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
434 if (info_ptr
->valid
& PNG_INFO_bKGD
)
436 png_set_background(png_ptr
, &(info_ptr
->background
),
437 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
438 if ( info_ptr
->num_palette
> 0 )
439 bgindex
= info_ptr
->background
.index
;
442 png_set_background(png_ptr
, &my_background
,
443 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
445 // Added by JACS: guesswork!
446 if ( info_ptr
->num_trans
!= 0 )
447 bgindex
= info_ptr
->num_trans
- 1 ;
450 /* tell libpng to strip 16 bit depth files down to 8 bits */
451 if (info_ptr
->bit_depth
== 16)
452 png_set_strip_16(png_ptr
);
454 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
455 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
456 info_ptr
->color_type
);
458 if (info_ptr
->num_palette
>0)
460 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
463 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
464 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
465 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
467 byte
*row_pointers
= new byte
[row_stride
];
469 /* turn on interlace handling */
471 if (info_ptr
->interlace_type
)
472 number_passes
= png_set_interlace_handling(png_ptr
);
475 // printf("NP = %d ", number_passes);
477 // don't use the object to prevent warnings from VC++ about "unportable
478 // interaction between setjmp and C++ object destruction" (this is a correct
479 // warning, of course!)
480 wxPNGReaderIter
*iter
= new wxPNGReaderIter(this);
481 for (int pass
=0; pass
< number_passes
; pass
++)
486 //(unsigned char *)iter.GetRow();
487 if (info_ptr
->interlace_type
) {
489 iter
->GetRow(row_pointers
, row_stride
);
490 png_read_row(png_ptr
, row_pointers
, NULL
);
493 png_read_row(png_ptr
, row_pointers
, NULL
);
495 iter
->SetRow(row_pointers
, row_stride
);
497 } while(iter
->PrevRow());
498 // printf("Y=%d ",y);
502 delete[] row_pointers
;
504 /* read the rest of the file, getting any additional chunks
506 png_read_end(png_ptr
, info_ptr
);
508 /* clean up after the read, and free any memory allocated */
509 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
511 /* free the structures */
523 /* write a png file */
525 bool wxPNGReader::SaveFile(wxChar
* ImageFileName
)
528 wxStrcpy(filename
, ImageFileName
);
530 wxPNGReaderIter
iter(this);
536 fp
= fopen(wxConvFile
.cWX2MB(filename
), "wb");
540 /* allocate the necessary structures */
541 png_ptr
= new (png_struct
);
548 info_ptr
= new (png_info
);
556 /* set error handling */
557 if (setjmp(png_ptr
->jmpbuf
))
559 png_write_destroy(png_ptr
);
564 /* If we get here, we had a problem reading the file */
567 //png_set_error(ima_png_error, NULL);
569 // printf("writig pg %s ", filename);
570 /* initialize the structures */
571 png_info_init(info_ptr
);
572 png_write_init(png_ptr
);
574 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
575 /* set up the output control */
576 png_init_io(png_ptr
, fp
);
578 /* set the file information here */
579 info_ptr
->width
= GetWidth();
580 info_ptr
->height
= GetHeight();
581 info_ptr
->pixel_depth
= GetDepth();
582 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
583 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
584 info_ptr
->color_type
= GetColorType();
585 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
587 info_ptr
->rowbytes
= row_stride
;
590 // 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);
591 /* set the palette if there is one */
592 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
594 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
595 info_ptr
->valid
|= PNG_INFO_PLTE
;
596 info_ptr
->palette
= new png_color
[256];
597 info_ptr
->num_palette
= 256;
598 for (int i
=0; i
<256; i
++)
599 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
601 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
604 /* optional significant bit chunk */
605 // info_ptr->valid |= PNG_INFO_sBIT;
606 // info_ptr->sig_bit = true_bit_depth;
608 /* optional gamma chunk */
609 // info_ptr->valid |= PNG_INFO_gAMA;
610 // info_ptr->gamma = gamma;
612 /* other optional chunks */
614 /* write the file information */
615 png_write_info(png_ptr
, info_ptr
);
617 /* set up the transformations you want. Note that these are
618 all optional. Only call them if you want them */
620 /* shift the pixels up to a legal bit depth and fill in
621 as appropriate to correctly scale the image */
622 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
624 /* pack pixels into bytes */
625 // png_set_packing(png_ptr);
627 /* flip bgr pixels to rgb */
628 // png_set_bgr(png_ptr);
630 /* swap bytes of 16 bit files to most significant bit first */
631 // png_set_swap(png_ptr);
633 /* get rid of filler bytes, pack rgb into 3 bytes */
634 // png_set_rgbx(png_ptr);
636 /* If you are only writing one row at a time, this works */
638 byte
*row_pointers
= new byte
[row_stride
];
641 // (unsigned char *)iter.GetRow();
642 iter
.GetRow(row_pointers
, row_stride
);
643 png_write_row(png_ptr
, row_pointers
);
644 } while(iter
.PrevRow());
646 delete[] row_pointers
;
648 /* write the rest of the file */
649 png_write_end(png_ptr
, info_ptr
);
651 /* clean up after the write, and free any memory allocated */
652 png_write_destroy(png_ptr
);
654 /* if you malloced the palette, free it here */
655 if (info_ptr
->palette
)
656 delete[] (info_ptr
->palette
);
658 /* free the structures */
669 static int Power(int x
, int y
)
673 for ( i
= 0; i
< y
; i
++)
680 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
681 'C', 'D', 'E', 'F' };
683 static void DecToHex(int dec
, char *buf
)
685 int firstDigit
= (int)(dec
/16.0);
686 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
687 buf
[0] = hexArray
[firstDigit
];
688 buf
[1] = hexArray
[secondDigit
];
693 bool wxPNGReader::SaveXPM(wxChar
*filename
, wxChar
*name
)
697 wxStrcpy(nameStr
, name
);
700 wxStrcpy(nameStr
, filename
);
701 wxStripExtension(nameStr
);
704 if ( GetDepth() > 4 )
706 // Only a depth of 4 and below allowed
713 ofstream
str(wxConvFile
.cWX2MB(filename
));
717 int noColours
= Power(2, GetDepth());
720 str
<< "/* XPM */\n";
721 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
722 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
725 int base
= 97 ; // start from 'a'
727 unsigned char red
, green
, blue
;
730 for ( i
= 0; i
< noColours
; i
++)
732 str
<< "\"" << (char)(base
+ i
) << " c #";
733 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
734 DecToHex(red
, hexBuf
);
736 DecToHex(green
, hexBuf
);
738 DecToHex(blue
, hexBuf
);
745 for ( y
= 0; y
< GetHeight(); y
++)
748 for ( x
= 0; x
< GetWidth(); x
++)
750 int index
= GetIndex(x
, y
);
751 str
<< (char)(base
+ index
) ;
762 #include <wx/os2/pnghand.h>
764 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
766 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
767 int desiredWidth
, int desiredHeight
)
770 if (reader
.ReadFile(WXSTRINGCAST name
))
772 return reader
.InstantiateBitmap(bitmap
);
778 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)