1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Implements a PNG reader class + handler
4 // Author: Julian Smart
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "pngread.h"
14 #pragma implementation "pnghand.h"
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
35 #include <wx/palette.h>
36 #include <wx/bitmap.h>
37 #include <wx/msw/pngread.h>
38 #include <wx/msw/dibutils.h>
41 #include "../png/png.h"
44 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
45 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
47 #ifndef GlobalAllocPtr
48 #define GlobalPtrHandle(lp) \
49 ((HGLOBAL)GlobalHandle(lp))
51 #define GlobalLockPtr(lp) \
52 ((BOOL)GlobalLock(GlobalPtrHandle(lp)))
53 #define GlobalUnlockPtr(lp) \
54 GlobalUnlock(GlobalPtrHandle(lp))
56 #define GlobalAllocPtr(flags, cb) \
57 (GlobalLock(GlobalAlloc((flags), (cb))))
58 #define GlobalReAllocPtr(lp, cbNew, flags) \
59 (GlobalUnlockPtr(lp), GlobalLock(GlobalReAlloc(GlobalPtrHandle(lp) , (cbNew), (flags))))
60 #define GlobalFreePtr(lp) \
61 (GlobalUnlockPtr(lp), (BOOL)GlobalFree(GlobalPtrHandle(lp)))
66 ima_png_error(png_struct
*png_ptr
, char *message
)
68 // wxMessageBox(message, "PNG error");
70 longjmp(png_ptr
->jmpbuf
, 1);
74 // static wxGifReaderIter* iter;
75 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
77 wxPNGReader::wxPNGReader()
80 RawImage
= NULL
; // Image data
82 Width
= 0; Height
= 0; // Dimensions
83 Depth
= 0; // (bits x pixel)
84 ColorType
= 0; // Bit 1 = Palette used
88 EfeWidth
= 0; // Efective Width
96 wxPNGReader::wxPNGReader ( wxChar
* ImageFileName
)
100 RawImage
= NULL
; // Image data
102 Width
= 0; Height
= 0; // Dimensions
103 Depth
= 0; // (bits x pixel)
104 ColorType
= 0; // Bit 1 = Palette used
105 // Bit 2 = Color used
106 // Bit 3 = Alpha used
108 EfeWidth
= 0; // Efective Width
114 imageOK
= ReadFile (ImageFileName
);
118 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
120 Width
= width
; Height
= height
; Depth
= depth
;
121 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
125 GlobalFreePtr((unsigned int) lpbi
);
133 lpbi
= DibCreate(Depth
, Width
, Height
);
135 RawImage
= (ImagePointerType
)DibPtr(lpbi
);
136 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
141 wxPNGReader::~wxPNGReader ( )
145 GlobalFreePtr((unsigned int) lpbi
);
154 int wxPNGReader::GetIndex(int x
, int y
)
156 if (!Inside(x
, y
) || (Depth
>8)) return -1;
158 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
159 int index
= (int)(*ImagePointer
);
163 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
165 if (!Inside(x
, y
)) return FALSE
;
168 return Palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
169 /* PALETTEENTRY entry;
170 ::GetPaletteEntries((HPALETTE) Palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
173 *b = entry.peBlue; */
175 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
176 *b
= ImagePointer
[0];
177 *g
= ImagePointer
[1];
178 *r
= ImagePointer
[2];
184 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
186 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
188 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
189 *ImagePointer
= index
;
194 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
196 if (!Inside(x
, y
)) return FALSE
;
198 if (ColorType
& COLORTYPE_PALETTE
)
200 if (!Palette
) return FALSE
;
201 SetIndex(x
, y
, Palette
->GetPixel(r
, g
, b
));
204 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
213 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
217 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
219 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
223 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
225 Palette
= new wxPalette();
231 Palette
->Create(n
, r
, g
, b
);
232 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
233 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
237 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
239 Palette
= new wxPalette();
243 byte r
[256], g
[256], b
[256];
245 for(int i
=0; i
<n
; i
++)
247 r
[i
] = rgb_struct
[i
].red
;
248 g
[i
] = rgb_struct
[i
].green
;
249 b
[i
] = rgb_struct
[i
].blue
;
251 // Added by JACS copying from Andrew Davison's additions
252 // to GIF-reading code
253 // Make transparency colour black...
255 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
257 Palette
->Create(n
, r
, g
, b
);
258 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
259 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
262 void wxPNGReader::NullData()
268 wxBitmap
* wxPNGReader::GetBitmap()
270 wxBitmap
*bitmap
= new wxBitmap
;
271 if ( InstantiateBitmap(bitmap
) )
280 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
282 HDC dc
= ::CreateCompatibleDC(NULL
);
286 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
287 // is a memory dc that must have a bitmap selected into it)
288 HDC dc2
= GetDC(NULL
);
289 HBITMAP tmpBitmap
= ::CreateCompatibleBitmap(dc2
, GetWidth(), GetHeight());
290 ReleaseDC(NULL
, dc2
);
291 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, tmpBitmap
);
295 ::SelectPalette(dc
, (HPALETTE
) Palette
->GetHPALETTE(), FALSE
);
296 ::RealizePalette(dc
);
299 HBITMAP hBitmap
= ::CreateDIBitmap(dc
, lpbi
,
300 CBM_INIT
, RawImage
, (LPBITMAPINFO
) lpbi
, DIB_PAL_COLORS
);
302 ::SelectPalette(dc
, NULL
, TRUE
);
303 ::SelectObject(dc
, oldBitmap
);
304 ::DeleteObject(tmpBitmap
);
309 bitmap
->SetHBITMAP((WXHBITMAP
) hBitmap
);
310 bitmap
->SetWidth(GetWidth());
311 bitmap
->SetHeight(GetHeight());
312 bitmap
->SetDepth(GetDepth());
313 if ( GetDepth() > 1 && Palette
)
314 bitmap
->SetPalette(*Palette
);
318 // Make a mask if appropriate
321 wxMask
*mask
= CreateMask();
322 bitmap
->SetMask(mask
);
337 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
339 // To get number of entries...
341 ::GetObject((HPALETTE
) cmap
->GetHPALETTE(), sizeof(WORD
), &count
);
343 LOGPALETTE
* logPal
= (LOGPALETTE
*)
344 new BYTE
[sizeof(LOGPALETTE
) + count
*sizeof(PALETTEENTRY
)];
345 logPal
->palVersion
= 0x300;
346 logPal
->palNumEntries
= count
;
347 ::GetPaletteEntries((HPALETTE
) cmap
->GetHPALETTE(), 0, count
, logPal
->palPalEntry
);
349 HPALETTE hPalette
= ::CreatePalette(logPal
);
352 wxPalette
*newCmap
= new wxPalette
;
353 newCmap
->SetHPALETTE((WXHPALETTE
) hPalette
);
357 wxMask
*wxPNGReader::CreateMask()
359 HBITMAP hBitmap
= ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL
);
361 HDC dc
= ::CreateCompatibleDC(NULL
);
362 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, hBitmap
);
364 int bgIndex
= GetBGIndex();
368 for (x
=0; x
<GetWidth(); x
++)
370 for (y
=0; y
<GetHeight(); y
++)
372 int index
= GetIndex(x
, y
);
373 if ( index
== bgIndex
)
374 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(0, 0, 0));
376 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(255, 255, 255));
380 ::SelectObject(dc
, oldBitmap
);
381 wxMask
*mask
= new wxMask
;
382 mask
->SetMaskBitmap((WXHBITMAP
) hBitmap
);
386 bool wxPNGReader::ReadFile(wxChar
* ImageFileName
)
391 wxStrcpy(filename
, ImageFileName
);
398 fp
= fopen(wxConvFile
.cWX2MB(filename
), "rb");
402 /* allocate the necessary structures */
403 png_ptr
= new (png_struct
);
410 info_ptr
= new (png_info
);
417 /* set error handling */
418 if (setjmp(png_ptr
->jmpbuf
))
420 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
425 /* If we get here, we had a problem reading the file */
428 //png_set_error(ima_png_error, NULL);
430 /* initialize the structures, info first for error handling */
431 png_info_init(info_ptr
);
432 png_read_init(png_ptr
);
434 /* set up the input control */
435 png_init_io(png_ptr
, fp
);
437 /* read the file information */
438 png_read_info(png_ptr
, info_ptr
);
440 /* allocate the memory to hold the image using the fields
442 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
444 if (info_ptr
->valid
& PNG_INFO_bKGD
)
446 png_set_background(png_ptr
, &(info_ptr
->background
),
447 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
448 if ( info_ptr
->num_palette
> 0 )
449 bgindex
= info_ptr
->background
.index
;
452 png_set_background(png_ptr
, &my_background
,
453 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
455 // Added by JACS: guesswork!
456 if ( info_ptr
->num_trans
!= 0 )
457 bgindex
= info_ptr
->num_trans
- 1 ;
460 /* tell libpng to strip 16 bit depth files down to 8 bits */
461 if (info_ptr
->bit_depth
== 16)
462 png_set_strip_16(png_ptr
);
464 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
465 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
466 info_ptr
->color_type
);
468 if (info_ptr
->num_palette
>0)
470 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
473 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
474 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
475 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
477 byte
*row_pointers
= new byte
[row_stride
];
479 /* turn on interlace handling */
480 if (info_ptr
->interlace_type
)
481 number_passes
= png_set_interlace_handling(png_ptr
);
484 // printf("NP = %d ", number_passes);
486 // don't use the object to prevent warnings from VC++ about "unportable
487 // interaction between setjmp and C++ object destruction" (this is a correct
488 // warning, of course!)
489 wxPNGReaderIter
*iter
= new wxPNGReaderIter(this);
490 for (int pass
=0; pass
< number_passes
; pass
++)
495 //(unsigned char *)iter.GetRow();
496 if (info_ptr
->interlace_type
) {
498 iter
->GetRow(row_pointers
, row_stride
);
499 png_read_row(png_ptr
, row_pointers
, NULL
);
502 png_read_row(png_ptr
, row_pointers
, NULL
);
504 iter
->SetRow(row_pointers
, row_stride
);
506 } while(iter
->PrevRow());
507 // printf("Y=%d ",y);
511 delete[] row_pointers
;
513 /* read the rest of the file, getting any additional chunks
515 png_read_end(png_ptr
, info_ptr
);
517 /* clean up after the read, and free any memory allocated */
518 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
520 /* free the structures */
532 /* write a png file */
534 bool wxPNGReader::SaveFile(wxChar
* ImageFileName
)
537 wxStrcpy(filename
, ImageFileName
);
539 wxPNGReaderIter
iter(this);
545 fp
= fopen(wxConvFile
.cWX2MB(filename
), "wb");
549 /* allocate the necessary structures */
550 png_ptr
= new (png_struct
);
557 info_ptr
= new (png_info
);
565 /* set error handling */
566 if (setjmp(png_ptr
->jmpbuf
))
568 png_write_destroy(png_ptr
);
573 /* If we get here, we had a problem reading the file */
576 //png_set_error(ima_png_error, NULL);
578 // printf("writig pg %s ", filename);
579 /* initialize the structures */
580 png_info_init(info_ptr
);
581 png_write_init(png_ptr
);
583 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
584 /* set up the output control */
585 png_init_io(png_ptr
, fp
);
587 /* set the file information here */
588 info_ptr
->width
= GetWidth();
589 info_ptr
->height
= GetHeight();
590 info_ptr
->pixel_depth
= GetDepth();
591 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
592 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
593 info_ptr
->color_type
= GetColorType();
594 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
596 info_ptr
->rowbytes
= row_stride
;
599 // 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);
600 /* set the palette if there is one */
601 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
603 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
604 info_ptr
->valid
|= PNG_INFO_PLTE
;
605 info_ptr
->palette
= new png_color
[256];
606 info_ptr
->num_palette
= 256;
607 for (int i
=0; i
<256; i
++)
608 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
610 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
613 /* optional significant bit chunk */
614 // info_ptr->valid |= PNG_INFO_sBIT;
615 // info_ptr->sig_bit = true_bit_depth;
617 /* optional gamma chunk */
618 // info_ptr->valid |= PNG_INFO_gAMA;
619 // info_ptr->gamma = gamma;
621 /* other optional chunks */
623 /* write the file information */
624 png_write_info(png_ptr
, info_ptr
);
626 /* set up the transformations you want. Note that these are
627 all optional. Only call them if you want them */
629 /* shift the pixels up to a legal bit depth and fill in
630 as appropriate to correctly scale the image */
631 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
633 /* pack pixels into bytes */
634 // png_set_packing(png_ptr);
636 /* flip bgr pixels to rgb */
637 // png_set_bgr(png_ptr);
639 /* swap bytes of 16 bit files to most significant bit first */
640 // png_set_swap(png_ptr);
642 /* get rid of filler bytes, pack rgb into 3 bytes */
643 // png_set_rgbx(png_ptr);
645 /* If you are only writing one row at a time, this works */
647 byte
*row_pointers
= new byte
[row_stride
];
650 // (unsigned char *)iter.GetRow();
651 iter
.GetRow(row_pointers
, row_stride
);
652 png_write_row(png_ptr
, row_pointers
);
653 } while(iter
.PrevRow());
655 delete[] row_pointers
;
657 /* write the rest of the file */
658 png_write_end(png_ptr
, info_ptr
);
660 /* clean up after the write, and free any memory allocated */
661 png_write_destroy(png_ptr
);
663 /* if you malloced the palette, free it here */
664 if (info_ptr
->palette
)
665 delete[] (info_ptr
->palette
);
667 /* free the structures */
678 static int Power(int x
, int y
)
682 for ( i
= 0; i
< y
; i
++)
689 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
690 'C', 'D', 'E', 'F' };
692 static void DecToHex(int dec
, char *buf
)
694 int firstDigit
= (int)(dec
/16.0);
695 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
696 buf
[0] = hexArray
[firstDigit
];
697 buf
[1] = hexArray
[secondDigit
];
702 bool wxPNGReader::SaveXPM(wxChar
*filename
, wxChar
*name
)
706 wxStrcpy(nameStr
, name
);
709 wxStrcpy(nameStr
, filename
);
710 wxStripExtension(nameStr
);
713 if ( GetDepth() > 4 )
715 // Only a depth of 4 and below allowed
722 ofstream
str(wxConvFile
.cWX2MB(filename
));
726 int noColours
= Power(2, GetDepth());
729 str
<< "/* XPM */\n";
730 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
731 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
734 int base
= 97 ; // start from 'a'
736 unsigned char red
, green
, blue
;
739 for ( i
= 0; i
< noColours
; i
++)
741 str
<< "\"" << (char)(base
+ i
) << " c #";
742 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
743 DecToHex(red
, hexBuf
);
745 DecToHex(green
, hexBuf
);
747 DecToHex(blue
, hexBuf
);
754 for ( y
= 0; y
< GetHeight(); y
++)
757 for ( x
= 0; x
< GetWidth(); x
++)
759 int index
= GetIndex(x
, y
);
760 str
<< (char)(base
+ index
) ;
771 #include <wx/msw/pnghand.h>
773 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
775 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
776 int desiredWidth
, int desiredHeight
)
779 if (reader
.ReadFile(WXSTRINGCAST name
))
781 return reader
.InstantiateBitmap(bitmap
);
787 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)