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(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 ( 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(void)
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(void)
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
);
396 wxPNGReaderIter
iter(this);
399 fp
= fopen(wxConvFile
.cWX2MB(filename
), "rb");
403 /* allocate the necessary structures */
404 png_ptr
= new (png_struct
);
411 info_ptr
= new (png_info
);
418 /* set error handling */
419 if (setjmp(png_ptr
->jmpbuf
))
421 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
426 /* If we get here, we had a problem reading the file */
429 //png_set_error(ima_png_error, NULL);
431 /* initialize the structures, info first for error handling */
432 png_info_init(info_ptr
);
433 png_read_init(png_ptr
);
435 /* set up the input control */
436 png_init_io(png_ptr
, fp
);
438 /* read the file information */
439 png_read_info(png_ptr
, info_ptr
);
441 /* allocate the memory to hold the image using the fields
443 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
445 if (info_ptr
->valid
& PNG_INFO_bKGD
)
447 png_set_background(png_ptr
, &(info_ptr
->background
),
448 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
449 if ( info_ptr
->num_palette
> 0 )
450 bgindex
= info_ptr
->background
.index
;
453 png_set_background(png_ptr
, &my_background
,
454 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
456 // Added by JACS: guesswork!
457 if ( info_ptr
->num_trans
!= 0 )
458 bgindex
= info_ptr
->num_trans
- 1 ;
461 /* tell libpng to strip 16 bit depth files down to 8 bits */
462 if (info_ptr
->bit_depth
== 16)
463 png_set_strip_16(png_ptr
);
465 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
466 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
467 info_ptr
->color_type
);
469 if (info_ptr
->num_palette
>0)
471 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
474 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
475 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
476 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
478 byte
*row_pointers
= new byte
[row_stride
];
480 /* turn on interlace handling */
481 if (info_ptr
->interlace_type
)
482 number_passes
= png_set_interlace_handling(png_ptr
);
485 // printf("NP = %d ", number_passes);
487 for (int pass
=0; pass
< number_passes
; pass
++) {
491 // (unsigned char *)iter.GetRow();
492 if (info_ptr
->interlace_type
) {
494 iter
.GetRow(row_pointers
, row_stride
);
495 png_read_row(png_ptr
, row_pointers
, NULL
);
498 png_read_row(png_ptr
, row_pointers
, NULL
);
500 iter
.SetRow(row_pointers
, row_stride
);
502 } while(iter
.PrevRow());
503 // printf("Y=%d ",y);
505 delete[] row_pointers
;
507 /* read the rest of the file, getting any additional chunks
509 png_read_end(png_ptr
, info_ptr
);
511 /* clean up after the read, and free any memory allocated */
512 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
514 /* free the structures */
526 /* write a png file */
528 bool wxPNGReader::SaveFile(wxChar
* ImageFileName
)
531 wxStrcpy(filename
, ImageFileName
);
533 wxPNGReaderIter
iter(this);
539 fp
= fopen(wxConvFile
.cWX2MB(filename
), "wb");
543 /* allocate the necessary structures */
544 png_ptr
= new (png_struct
);
551 info_ptr
= new (png_info
);
559 /* set error handling */
560 if (setjmp(png_ptr
->jmpbuf
))
562 png_write_destroy(png_ptr
);
567 /* If we get here, we had a problem reading the file */
570 //png_set_error(ima_png_error, NULL);
572 // printf("writig pg %s ", filename);
573 /* initialize the structures */
574 png_info_init(info_ptr
);
575 png_write_init(png_ptr
);
577 int row_stride
= GetWidth() * ((GetDepth()+7)>>3);
578 /* set up the output control */
579 png_init_io(png_ptr
, fp
);
581 /* set the file information here */
582 info_ptr
->width
= GetWidth();
583 info_ptr
->height
= GetHeight();
584 info_ptr
->pixel_depth
= GetDepth();
585 info_ptr
->channels
= (GetDepth()>8) ? 3: 1;
586 info_ptr
->bit_depth
= GetDepth()/info_ptr
->channels
;
587 info_ptr
->color_type
= GetColorType();
588 info_ptr
->compression_type
= info_ptr
->filter_type
= info_ptr
->interlace_type
=0;
590 info_ptr
->rowbytes
= row_stride
;
593 // 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);
594 /* set the palette if there is one */
595 if ((GetColorType() & COLORTYPE_PALETTE
) && GetPalette())
597 // printf("writing paleta[%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
598 info_ptr
->valid
|= PNG_INFO_PLTE
;
599 info_ptr
->palette
= new png_color
[256];
600 info_ptr
->num_palette
= 256;
601 for (int i
=0; i
<256; i
++)
602 GetPalette()->GetRGB(i
, &info_ptr
->palette
[i
].red
, &info_ptr
->palette
[i
].green
, &info_ptr
->palette
[i
].blue
);
604 // printf("Paleta [%d %d %x]",GetColorType() ,COLORTYPE_PALETTE, GetPalette());
607 /* optional significant bit chunk */
608 // info_ptr->valid |= PNG_INFO_sBIT;
609 // info_ptr->sig_bit = true_bit_depth;
611 /* optional gamma chunk */
612 // info_ptr->valid |= PNG_INFO_gAMA;
613 // info_ptr->gamma = gamma;
615 /* other optional chunks */
617 /* write the file information */
618 png_write_info(png_ptr
, info_ptr
);
620 /* set up the transformations you want. Note that these are
621 all optional. Only call them if you want them */
623 /* shift the pixels up to a legal bit depth and fill in
624 as appropriate to correctly scale the image */
625 // png_set_shift(png_ptr, &(info_ptr->sig_bit));
627 /* pack pixels into bytes */
628 // png_set_packing(png_ptr);
630 /* flip bgr pixels to rgb */
631 // png_set_bgr(png_ptr);
633 /* swap bytes of 16 bit files to most significant bit first */
634 // png_set_swap(png_ptr);
636 /* get rid of filler bytes, pack rgb into 3 bytes */
637 // png_set_rgbx(png_ptr);
639 /* If you are only writing one row at a time, this works */
641 byte
*row_pointers
= new byte
[row_stride
];
644 // (unsigned char *)iter.GetRow();
645 iter
.GetRow(row_pointers
, row_stride
);
646 png_write_row(png_ptr
, row_pointers
);
647 } while(iter
.PrevRow());
649 delete[] row_pointers
;
651 /* write the rest of the file */
652 png_write_end(png_ptr
, info_ptr
);
654 /* clean up after the write, and free any memory allocated */
655 png_write_destroy(png_ptr
);
657 /* if you malloced the palette, free it here */
658 if (info_ptr
->palette
)
659 delete[] (info_ptr
->palette
);
661 /* free the structures */
672 static int Power(int x
, int y
)
676 for ( i
= 0; i
< y
; i
++)
683 static char hexArray
[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
684 'C', 'D', 'E', 'F' };
686 static void DecToHex(int dec
, char *buf
)
688 int firstDigit
= (int)(dec
/16.0);
689 int secondDigit
= (int)(dec
- (firstDigit
*16.0));
690 buf
[0] = hexArray
[firstDigit
];
691 buf
[1] = hexArray
[secondDigit
];
696 bool wxPNGReader::SaveXPM(wxChar
*filename
, wxChar
*name
)
700 wxStrcpy(nameStr
, name
);
703 wxStrcpy(nameStr
, filename
);
704 wxStripExtension(nameStr
);
707 if ( GetDepth() > 4 )
709 // Only a depth of 4 and below allowed
716 ofstream
str(wxConvFile
.cWX2MB(filename
));
720 int noColours
= Power(2, GetDepth());
723 str
<< "/* XPM */\n";
724 str
<< "static char * " << nameStr
<< "_xpm[] = {\n";
725 str
<< "\"" << GetWidth() << " " << GetHeight() << " " << noColours
<< " 1\",\n";
728 int base
= 97 ; // start from 'a'
730 unsigned char red
, green
, blue
;
733 for ( i
= 0; i
< noColours
; i
++)
735 str
<< "\"" << (char)(base
+ i
) << " c #";
736 GetPalette()->GetRGB(i
, &red
, &green
, &blue
);
737 DecToHex(red
, hexBuf
);
739 DecToHex(green
, hexBuf
);
741 DecToHex(blue
, hexBuf
);
748 for ( y
= 0; y
< GetHeight(); y
++)
751 for ( x
= 0; x
< GetWidth(); x
++)
753 int index
= GetIndex(x
, y
);
754 str
<< (char)(base
+ index
) ;
765 #include <wx/msw/pnghand.h>
767 IMPLEMENT_DYNAMIC_CLASS(wxPNGFileHandler
, wxBitmapHandler
)
769 bool wxPNGFileHandler::LoadFile(wxBitmap
*bitmap
, const wxString
& name
, long flags
,
770 int desiredWidth
, int desiredHeight
)
773 if (reader
.ReadFile(WXSTRINGCAST name
))
775 return reader
.InstantiateBitmap(bitmap
);
781 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)