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>
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(void)
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 ( char* 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 if (lpbi
= DibCreate(Depth
, Width
, Height
)) {
134 RawImage
= (ImagePointerType
)DibPtr(lpbi
);
135 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
140 wxPNGReader::~wxPNGReader ( )
144 GlobalFreePtr((unsigned int) lpbi
);
153 int wxPNGReader::GetIndex(int x
, int y
)
155 if (!Inside(x
, y
) || (Depth
>8)) return -1;
157 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
158 int index
= (int)(*ImagePointer
);
162 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
164 if (!Inside(x
, y
)) return FALSE
;
167 return Palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
168 /* PALETTEENTRY entry;
169 ::GetPaletteEntries((HPALETTE) Palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
172 *b = entry.peBlue; */
174 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
175 *b
= ImagePointer
[0];
176 *g
= ImagePointer
[1];
177 *r
= ImagePointer
[2];
183 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
185 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
187 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
188 *ImagePointer
= index
;
193 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
195 if (!Inside(x
, y
)) return FALSE
;
197 if (ColorType
& COLORTYPE_PALETTE
)
199 if (!Palette
) return FALSE
;
200 SetIndex(x
, y
, Palette
->GetPixel(r
, g
, b
));
203 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
212 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
216 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
218 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
222 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
224 Palette
= new wxPalette();
230 Palette
->Create(n
, r
, g
, b
);
231 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
232 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
236 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
238 Palette
= new wxPalette();
242 byte r
[256], g
[256], b
[256];
244 for(int i
=0; i
<n
; i
++)
246 r
[i
] = rgb_struct
[i
].red
;
247 g
[i
] = rgb_struct
[i
].green
;
248 b
[i
] = rgb_struct
[i
].blue
;
250 // Added by JACS copying from Andrew Davison's additions
251 // to GIF-reading code
252 // Make transparency colour black...
254 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
256 Palette
->Create(n
, r
, g
, b
);
257 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
258 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
261 void wxPNGReader::NullData()
267 wxBitmap
* wxPNGReader::GetBitmap(void)
269 wxBitmap
*bitmap
= new wxBitmap
;
270 if ( InstantiateBitmap(bitmap
) )
279 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
281 HDC dc
= ::CreateCompatibleDC(NULL
);
285 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
286 // is a memory dc that must have a bitmap selected into it)
287 HDC dc2
= GetDC(NULL
);
288 HBITMAP tmpBitmap
= ::CreateCompatibleBitmap(dc2
, GetWidth(), GetHeight());
289 ReleaseDC(NULL
, dc2
);
290 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, tmpBitmap
);
294 HPALETTE oldPal
= ::SelectPalette(dc
, (HPALETTE
) Palette
->GetHPALETTE(), FALSE
);
295 ::RealizePalette(dc
);
298 HBITMAP hBitmap
= ::CreateDIBitmap(dc
, lpbi
,
299 CBM_INIT
, RawImage
, (LPBITMAPINFO
) lpbi
, DIB_PAL_COLORS
);
301 ::SelectPalette(dc
, NULL
, TRUE
);
302 ::SelectObject(dc
, oldBitmap
);
303 ::DeleteObject(tmpBitmap
);
308 bitmap
->SetHBITMAP((WXHBITMAP
) hBitmap
);
309 bitmap
->SetWidth(GetWidth());
310 bitmap
->SetHeight(GetHeight());
311 bitmap
->SetDepth(GetDepth());
312 if ( GetDepth() > 1 && Palette
)
313 bitmap
->SetPalette(*Palette
);
317 // Make a mask if appropriate
320 wxMask
*mask
= CreateMask();
321 bitmap
->SetMask(mask
);
336 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
338 // To get number of entries...
340 ::GetObject((HPALETTE
) cmap
->GetHPALETTE(), sizeof(WORD
), &count
);
342 LOGPALETTE
* logPal
= (LOGPALETTE
*)
343 new BYTE
[sizeof(LOGPALETTE
) + count
*sizeof(PALETTEENTRY
)];
344 logPal
->palVersion
= 0x300;
345 logPal
->palNumEntries
= count
;
346 ::GetPaletteEntries((HPALETTE
) cmap
->GetHPALETTE(), 0, count
, logPal
->palPalEntry
);
348 HPALETTE hPalette
= ::CreatePalette(logPal
);
351 wxPalette
*newCmap
= new wxPalette
;
352 newCmap
->SetHPALETTE((WXHPALETTE
) hPalette
);
356 wxMask
*wxPNGReader::CreateMask(void)
358 HBITMAP hBitmap
= ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL
);
360 HDC dc
= ::CreateCompatibleDC(NULL
);
361 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, hBitmap
);
363 int bgIndex
= GetBGIndex();
367 for (x
=0; x
<GetWidth(); x
++)
369 for (y
=0; y
<GetHeight(); y
++)
371 int index
= GetIndex(x
, y
);
372 if ( index
== bgIndex
)
373 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(0, 0, 0));
375 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(255, 255, 255));
379 ::SelectObject(dc
, oldBitmap
);
380 wxMask
*mask
= new wxMask
;
381 mask
->SetMaskBitmap((WXHBITMAP
) hBitmap
);
385 bool wxPNGReader::ReadFile(char * ImageFileName
)
390 strcpy(filename
, ImageFileName
);
395 wxPNGReaderIter
iter(this);
398 fp
= fopen(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 for (int pass
=0; pass
< number_passes
; pass
++) {
490 // (unsigned char *)iter.GetRow();
491 if (info_ptr
->interlace_type
) {
493 iter
.GetRow(row_pointers
, row_stride
);
494 png_read_row(png_ptr
, row_pointers
, NULL
);
497 png_read_row(png_ptr
, row_pointers
, NULL
);
499 iter
.SetRow(row_pointers
, row_stride
);
501 } while(iter
.PrevRow());
502 // printf("Y=%d ",y);
504 delete[] row_pointers
;
506 /* read the rest of the file, getting any additional chunks
508 png_read_end(png_ptr
, info_ptr
);
510 /* clean up after the read, and free any memory allocated */
511 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
513 /* free the structures */
525 /* write a png file */
527 bool wxPNGReader::SaveFile(char * ImageFileName
)
530 strcpy(filename
, ImageFileName
);
532 wxPNGReaderIter
iter(this);
538 fp
= fopen(filename
, "wb");
542 /* allocate the necessary structures */
543 png_ptr
= new (png_struct
);
550 info_ptr
= new (png_info
);
558 /* set error handling */
559 if (setjmp(png_ptr
->jmpbuf
))
561 png_write_destroy(png_ptr
);
566 /* If we get here, we had a problem reading the file */
569 //png_set_error(ima_png_error, NULL);
571 // printf("writig pg %s ", filename);
572 /* initialize the structures */
573 png_info_init(info_ptr
);
574 png_write_init(png_ptr
);
576 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
577 /* set up the output control */
578 png_init_io(png_ptr
, fp
);
580 /* set the file information here */
581 info_ptr
->width
= GetWidth();
582 info_ptr
->height
= GetHeight();
583 info_ptr
->pixel_depth
= GetDepth();
584 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
585 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
586 info_ptr
->color_type
= GetColorType();
587 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
589 info_ptr
->rowbytes
= row_stride
;
592 // 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);
593 /* set the palette if there is one */
594 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
596 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
597 info_ptr
->valid
|= PNG_INFO_PLTE
;
598 info_ptr
->palette
= new png_color
[256];
599 info_ptr
->num_palette
= 256;
600 for (int i
=0; i
<256; i
++)
601 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
603 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
606 /* optional significant bit chunk */
607 // info_ptr->valid |= PNG_INFO_sBIT;
608 // info_ptr->sig_bit = true_bit_depth;
610 /* optional gamma chunk */
611 // info_ptr->valid |= PNG_INFO_gAMA;
612 // info_ptr->gamma = gamma;
614 /* other optional chunks */
616 /* write the file information */
617 png_write_info(png_ptr
, info_ptr
);
619 /* set up the transformations you want. Note that these are
620 all optional. Only call them if you want them */
622 /* shift the pixels up to a legal bit depth and fill in
623 as appropriate to correctly scale the image */
624 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
626 /* pack pixels into bytes */
627 // png_set_packing(png_ptr);
629 /* flip bgr pixels to rgb */
630 // png_set_bgr(png_ptr);
632 /* swap bytes of 16 bit files to most significant bit first */
633 // png_set_swap(png_ptr);
635 /* get rid of filler bytes, pack rgb into 3 bytes */
636 // png_set_rgbx(png_ptr);
638 /* If you are only writing one row at a time, this works */
640 byte
*row_pointers
= new byte
[row_stride
];
643 // (unsigned char *)iter.GetRow();
644 iter
.GetRow(row_pointers
, row_stride
);
645 png_write_row(png_ptr
, row_pointers
);
646 } while(iter
.PrevRow());
648 delete[] row_pointers
;
650 /* write the rest of the file */
651 png_write_end(png_ptr
, info_ptr
);
653 /* clean up after the write, and free any memory allocated */
654 png_write_destroy(png_ptr
);
656 /* if you malloced the palette, free it here */
657 if (info_ptr
->palette
)
658 delete[] (info_ptr
->palette
);
660 /* free the structures */
671 static int Power(int x
, int y
)
675 for ( i
= 0; i
< y
; i
++)
682 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
683 'C', 'D', 'E', 'F' };
685 static void DecToHex(int dec
, char *buf
)
687 int firstDigit
= (int)(dec
/16.0);
688 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
689 buf
[0] = hexArray
[firstDigit
];
690 buf
[1] = hexArray
[secondDigit
];
695 bool wxPNGReader::SaveXPM(char *filename
, char *name
)
699 strcpy(nameStr
, name
);
702 strcpy(nameStr
, filename
);
703 wxStripExtension(nameStr
);
706 if ( GetDepth() > 4 )
708 // Only a depth of 4 and below allowed
715 ofstream
str(filename
);
719 int noColours
= Power(2, GetDepth());
722 str
<< "/* XPM */\n";
723 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
724 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
727 int base
= 97 ; // start from 'a'
729 unsigned char red
, green
, blue
;
732 for ( i
= 0; i
< noColours
; i
++)
734 str
<< "\"" << (char)(base
+ i
) << " c #";
735 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
736 DecToHex(red
, hexBuf
);
738 DecToHex(green
, hexBuf
);
740 DecToHex(blue
, hexBuf
);
747 for ( y
= 0; y
< GetHeight(); y
++)
750 for ( x
= 0; x
< GetWidth(); x
++)
752 int index
= GetIndex(x
, y
);
753 str
<< (char)(base
+ index
) ;
764 #include <wx/msw/pnghand.h>
766 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
768 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
769 int desiredWidth
, int desiredHeight
)
772 if (reader
.ReadFile((char*) (const char*) name
))
774 return reader
.InstantiateBitmap(bitmap
);
780 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)