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"
38 #include <wx/palette.h>
39 #include <wx/bitmap.h>
40 #include <wx/msw/pngread.h>
41 #include <wx/msw/dibutils.h>
47 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
48 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
50 #ifndef GlobalAllocPtr
51 #define GlobalPtrHandle(lp) \
52 ((HGLOBAL)GlobalHandle(lp))
54 #define GlobalLockPtr(lp) \
55 ((BOOL)GlobalLock(GlobalPtrHandle(lp)))
56 #define GlobalUnlockPtr(lp) \
57 GlobalUnlock(GlobalPtrHandle(lp))
59 #define GlobalAllocPtr(flags, cb) \
60 (GlobalLock(GlobalAlloc((flags), (cb))))
61 #define GlobalReAllocPtr(lp, cbNew, flags) \
62 (GlobalUnlockPtr(lp), GlobalLock(GlobalReAlloc(GlobalPtrHandle(lp) , (cbNew), (flags))))
63 #define GlobalFreePtr(lp) \
64 (GlobalUnlockPtr(lp), (BOOL)GlobalFree(GlobalPtrHandle(lp)))
69 ima_png_error(png_struct
*png_ptr
, char *message
)
71 // wxMessageBox(message, "PNG error");
73 longjmp(png_ptr
->jmpbuf
, 1);
77 // static wxGifReaderIter* iter;
78 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
80 wxPNGReader::wxPNGReader(void)
83 RawImage
= NULL
; // Image data
85 Width
= 0; Height
= 0; // Dimensions
86 Depth
= 0; // (bits x pixel)
87 ColorType
= 0; // Bit 1 = Palette used
91 EfeWidth
= 0; // Efective Width
99 wxPNGReader::wxPNGReader ( char* ImageFileName
)
103 RawImage
= NULL
; // Image data
105 Width
= 0; Height
= 0; // Dimensions
106 Depth
= 0; // (bits x pixel)
107 ColorType
= 0; // Bit 1 = Palette used
108 // Bit 2 = Color used
109 // Bit 3 = Alpha used
111 EfeWidth
= 0; // Efective Width
117 imageOK
= ReadFile (ImageFileName
);
121 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
123 Width
= width
; Height
= height
; Depth
= depth
;
124 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
128 GlobalFreePtr((unsigned int) lpbi
);
136 if (lpbi
= DibCreate(Depth
, Width
, Height
)) {
137 RawImage
= (ImagePointerType
)DibPtr(lpbi
);
138 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
143 wxPNGReader::~wxPNGReader ( )
147 GlobalFreePtr((unsigned int) lpbi
);
156 int wxPNGReader::GetIndex(int x
, int y
)
158 if (!Inside(x
, y
) || (Depth
>8)) return -1;
160 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
161 int index
= (int)(*ImagePointer
);
165 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
167 if (!Inside(x
, y
)) return FALSE
;
170 return Palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
171 /* PALETTEENTRY entry;
172 ::GetPaletteEntries((HPALETTE) Palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
175 *b = entry.peBlue; */
177 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
178 *b
= ImagePointer
[0];
179 *g
= ImagePointer
[1];
180 *r
= ImagePointer
[2];
186 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
188 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
190 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
191 *ImagePointer
= index
;
196 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
198 if (!Inside(x
, y
)) return FALSE
;
200 if (ColorType
& COLORTYPE_PALETTE
)
202 if (!Palette
) return FALSE
;
203 SetIndex(x
, y
, Palette
->GetPixel(r
, g
, b
));
206 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
215 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
219 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
221 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
225 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
227 Palette
= new wxPalette();
233 Palette
->Create(n
, r
, g
, b
);
234 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
235 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
239 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
241 Palette
= new wxPalette();
245 byte r
[256], g
[256], b
[256];
247 for(int i
=0; i
<n
; i
++)
249 r
[i
] = rgb_struct
[i
].red
;
250 g
[i
] = rgb_struct
[i
].green
;
251 b
[i
] = rgb_struct
[i
].blue
;
253 // Added by JACS copying from Andrew Davison's additions
254 // to GIF-reading code
255 // Make transparency colour black...
257 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
259 Palette
->Create(n
, r
, g
, b
);
260 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
261 return (DibSetUsage(lpbi
, (HPALETTE
) Palette
->GetHPALETTE(), WXIMA_COLORS
) != 0);
264 void wxPNGReader::NullData()
270 wxBitmap
* wxPNGReader::GetBitmap(void)
272 wxBitmap
*bitmap
= new wxBitmap
;
273 if ( InstantiateBitmap(bitmap
) )
282 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
284 HDC dc
= ::CreateCompatibleDC(NULL
);
288 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
289 // is a memory dc that must have a bitmap selected into it)
290 HDC dc2
= GetDC(NULL
);
291 HBITMAP tmpBitmap
= ::CreateCompatibleBitmap(dc2
, GetWidth(), GetHeight());
292 ReleaseDC(NULL
, dc2
);
293 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, tmpBitmap
);
297 HPALETTE oldPal
= ::SelectPalette(dc
, (HPALETTE
) Palette
->GetHPALETTE(), FALSE
);
298 ::RealizePalette(dc
);
301 HBITMAP hBitmap
= ::CreateDIBitmap(dc
, lpbi
,
302 CBM_INIT
, RawImage
, (LPBITMAPINFO
) lpbi
, DIB_PAL_COLORS
);
304 ::SelectPalette(dc
, NULL
, TRUE
);
305 ::SelectObject(dc
, oldBitmap
);
306 ::DeleteObject(tmpBitmap
);
311 bitmap
->SetHBITMAP((WXHBITMAP
) hBitmap
);
312 bitmap
->SetWidth(GetWidth());
313 bitmap
->SetHeight(GetHeight());
314 bitmap
->SetDepth(GetDepth());
315 if ( GetDepth() > 1 && Palette
)
316 bitmap
->SetPalette(*Palette
);
320 // Make a mask if appropriate
323 wxMask
*mask
= CreateMask();
324 bitmap
->SetMask(mask
);
339 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
341 // To get number of entries...
343 ::GetObject((HPALETTE
) cmap
->GetHPALETTE(), sizeof(WORD
), &count
);
345 LOGPALETTE
* logPal
= (LOGPALETTE
*)
346 new BYTE
[sizeof(LOGPALETTE
) + count
*sizeof(PALETTEENTRY
)];
347 logPal
->palVersion
= 0x300;
348 logPal
->palNumEntries
= count
;
349 ::GetPaletteEntries((HPALETTE
) cmap
->GetHPALETTE(), 0, count
, logPal
->palPalEntry
);
351 HPALETTE hPalette
= ::CreatePalette(logPal
);
354 wxPalette
*newCmap
= new wxPalette
;
355 newCmap
->SetHPALETTE((WXHPALETTE
) hPalette
);
359 wxMask
*wxPNGReader::CreateMask(void)
361 HBITMAP hBitmap
= ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL
);
363 HDC dc
= ::CreateCompatibleDC(NULL
);
364 HBITMAP oldBitmap
= (HBITMAP
) ::SelectObject(dc
, hBitmap
);
366 int bgIndex
= GetBGIndex();
370 for (x
=0; x
<GetWidth(); x
++)
372 for (y
=0; y
<GetHeight(); y
++)
374 int index
= GetIndex(x
, y
);
375 if ( index
== bgIndex
)
376 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(0, 0, 0));
378 ::SetPixel(dc
, x
, GetHeight() - y
- 1, RGB(255, 255, 255));
382 ::SelectObject(dc
, oldBitmap
);
383 wxMask
*mask
= new wxMask
;
384 mask
->SetMaskBitmap((WXHBITMAP
) hBitmap
);
388 bool wxPNGReader::ReadFile(char * ImageFileName
)
393 strcpy(filename
, ImageFileName
);
398 wxPNGReaderIter
iter(this);
401 fp
= fopen(filename
, "rb");
405 /* allocate the necessary structures */
406 png_ptr
= new (png_struct
);
413 info_ptr
= new (png_info
);
420 /* set error handling */
421 if (setjmp(png_ptr
->jmpbuf
))
423 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
428 /* If we get here, we had a problem reading the file */
431 //png_set_error(ima_png_error, NULL);
433 /* initialize the structures, info first for error handling */
434 png_info_init(info_ptr
);
435 png_read_init(png_ptr
);
437 /* set up the input control */
438 png_init_io(png_ptr
, fp
);
440 /* read the file information */
441 png_read_info(png_ptr
, info_ptr
);
443 /* allocate the memory to hold the image using the fields
445 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
447 if (info_ptr
->valid
& PNG_INFO_bKGD
)
449 png_set_background(png_ptr
, &(info_ptr
->background
),
450 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
451 if ( info_ptr
->num_palette
> 0 )
452 bgindex
= info_ptr
->background
.index
;
455 png_set_background(png_ptr
, &my_background
,
456 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
458 // Added by JACS: guesswork!
459 if ( info_ptr
->num_trans
!= 0 )
460 bgindex
= info_ptr
->num_trans
- 1 ;
463 /* tell libpng to strip 16 bit depth files down to 8 bits */
464 if (info_ptr
->bit_depth
== 16)
465 png_set_strip_16(png_ptr
);
467 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
468 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
469 info_ptr
->color_type
);
471 if (info_ptr
->num_palette
>0)
473 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
476 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
477 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
478 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
480 byte
*row_pointers
= new byte
[row_stride
];
482 /* turn on interlace handling */
483 if (info_ptr
->interlace_type
)
484 number_passes
= png_set_interlace_handling(png_ptr
);
487 // printf("NP = %d ", number_passes);
489 for (int pass
=0; pass
< number_passes
; pass
++) {
493 // (unsigned char *)iter.GetRow();
494 if (info_ptr
->interlace_type
) {
496 iter
.GetRow(row_pointers
, row_stride
);
497 png_read_row(png_ptr
, row_pointers
, NULL
);
500 png_read_row(png_ptr
, row_pointers
, NULL
);
502 iter
.SetRow(row_pointers
, row_stride
);
504 } while(iter
.PrevRow());
505 // printf("Y=%d ",y);
507 delete[] row_pointers
;
509 /* read the rest of the file, getting any additional chunks
511 png_read_end(png_ptr
, info_ptr
);
513 /* clean up after the read, and free any memory allocated */
514 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
516 /* free the structures */
528 /* write a png file */
530 bool wxPNGReader::SaveFile(char * ImageFileName
)
533 strcpy(filename
, ImageFileName
);
535 wxPNGReaderIter
iter(this);
541 fp
= fopen(filename
, "wb");
545 /* allocate the necessary structures */
546 png_ptr
= new (png_struct
);
553 info_ptr
= new (png_info
);
561 /* set error handling */
562 if (setjmp(png_ptr
->jmpbuf
))
564 png_write_destroy(png_ptr
);
569 /* If we get here, we had a problem reading the file */
572 //png_set_error(ima_png_error, NULL);
574 // printf("writig pg %s ", filename);
575 /* initialize the structures */
576 png_info_init(info_ptr
);
577 png_write_init(png_ptr
);
579 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
580 /* set up the output control */
581 png_init_io(png_ptr
, fp
);
583 /* set the file information here */
584 info_ptr
->width
= GetWidth();
585 info_ptr
->height
= GetHeight();
586 info_ptr
->pixel_depth
= GetDepth();
587 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
588 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
589 info_ptr
->color_type
= GetColorType();
590 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
592 info_ptr
->rowbytes
= row_stride
;
595 // 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);
596 /* set the palette if there is one */
597 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
599 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
600 info_ptr
->valid
|= PNG_INFO_PLTE
;
601 info_ptr
->palette
= new png_color
[256];
602 info_ptr
->num_palette
= 256;
603 for (int i
=0; i
<256; i
++)
604 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
606 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
609 /* optional significant bit chunk */
610 // info_ptr->valid |= PNG_INFO_sBIT;
611 // info_ptr->sig_bit = true_bit_depth;
613 /* optional gamma chunk */
614 // info_ptr->valid |= PNG_INFO_gAMA;
615 // info_ptr->gamma = gamma;
617 /* other optional chunks */
619 /* write the file information */
620 png_write_info(png_ptr
, info_ptr
);
622 /* set up the transformations you want. Note that these are
623 all optional. Only call them if you want them */
625 /* shift the pixels up to a legal bit depth and fill in
626 as appropriate to correctly scale the image */
627 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
629 /* pack pixels into bytes */
630 // png_set_packing(png_ptr);
632 /* flip bgr pixels to rgb */
633 // png_set_bgr(png_ptr);
635 /* swap bytes of 16 bit files to most significant bit first */
636 // png_set_swap(png_ptr);
638 /* get rid of filler bytes, pack rgb into 3 bytes */
639 // png_set_rgbx(png_ptr);
641 /* If you are only writing one row at a time, this works */
643 byte
*row_pointers
= new byte
[row_stride
];
646 // (unsigned char *)iter.GetRow();
647 iter
.GetRow(row_pointers
, row_stride
);
648 png_write_row(png_ptr
, row_pointers
);
649 } while(iter
.PrevRow());
651 delete[] row_pointers
;
653 /* write the rest of the file */
654 png_write_end(png_ptr
, info_ptr
);
656 /* clean up after the write, and free any memory allocated */
657 png_write_destroy(png_ptr
);
659 /* if you malloced the palette, free it here */
660 if (info_ptr
->palette
)
661 delete[] (info_ptr
->palette
);
663 /* free the structures */
674 static int Power(int x
, int y
)
678 for ( i
= 0; i
< y
; i
++)
685 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
686 'C', 'D', 'E', 'F' };
688 static void DecToHex(int dec
, char *buf
)
690 int firstDigit
= (int)(dec
/16.0);
691 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
692 buf
[0] = hexArray
[firstDigit
];
693 buf
[1] = hexArray
[secondDigit
];
698 bool wxPNGReader::SaveXPM(char *filename
, char *name
)
702 strcpy(nameStr
, name
);
705 strcpy(nameStr
, filename
);
706 wxStripExtension(nameStr
);
709 if ( GetDepth() > 4 )
711 // Only a depth of 4 and below allowed
718 ofstream
str(filename
);
722 int noColours
= Power(2, GetDepth());
725 str
<< "/* XPM */\n";
726 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
727 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
730 int base
= 97 ; // start from 'a'
732 unsigned char red
, green
, blue
;
735 for ( i
= 0; i
< noColours
; i
++)
737 str
<< "\"" << (char)(base
+ i
) << " c #";
738 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
739 DecToHex(red
, hexBuf
);
741 DecToHex(green
, hexBuf
);
743 DecToHex(blue
, hexBuf
);
750 for ( y
= 0; y
< GetHeight(); y
++)
753 for ( x
= 0; x
< GetWidth(); x
++)
755 int index
= GetIndex(x
, y
);
756 str
<< (char)(base
+ index
) ;
767 #include <wx/msw/pnghand.h>
769 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
771 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
772 int desiredWidth
, int desiredHeight
)
775 if (reader
.ReadFile((char*) (const char*) name
))
777 return reader
.InstantiateBitmap(bitmap
);
783 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)