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/os2/pngread.h"
35 #include "../png/png.h"
38 extern "C" void png_read_init
PNGARG((png_structp png_ptr
));
39 extern "C" void png_write_init
PNGARG((png_structp png_ptr
));
41 #ifndef GlobalAllocPtr
42 #define GlobalPtrHandle(lp) \
43 ((HGLOBAL)GlobalHandle(lp))
45 #define GlobalLockPtr(lp) \
46 ((BOOL)GlobalLock(GlobalPtrHandle(lp)))
47 #define GlobalUnlockPtr(lp) \
48 GlobalUnlock(GlobalPtrHandle(lp))
50 #define GlobalAllocPtr(flags, cb) \
51 (GlobalLock(GlobalAlloc((flags), (cb))))
52 #define GlobalReAllocPtr(lp, cbNew, flags) \
53 (GlobalUnlockPtr(lp), GlobalLock(GlobalReAlloc(GlobalPtrHandle(lp) , (cbNew), (flags))))
54 #define GlobalFreePtr(lp) \
55 (GlobalUnlockPtr(lp), (BOOL)GlobalFree(GlobalPtrHandle(lp)))
60 ima_png_error(png_struct
*png_ptr
, char *message
)
62 // wxMessageBox(message, "PNG error");
64 longjmp(png_ptr
->jmpbuf
, 1);
68 // static wxGifReaderIter* iter;
69 wxPalette
*wxCopyPalette(const wxPalette
*cmap
);
71 wxPNGReader::wxPNGReader()
74 RawImage
= NULL
; // Image data
76 Width
= 0; Height
= 0; // Dimensions
77 Depth
= 0; // (bits x pixel)
78 ColorType
= 0; // Bit 1 = Palette used
82 EfeWidth
= 0; // Efective Width
90 wxPNGReader::wxPNGReader ( wxChar
* ImageFileName
)
94 RawImage
= NULL
; // Image data
96 Width
= 0; Height
= 0; // Dimensions
97 Depth
= 0; // (bits x pixel)
98 ColorType
= 0; // Bit 1 = Palette used
100 // Bit 3 = Alpha used
102 EfeWidth
= 0; // Efective Width
108 imageOK
= ReadFile (ImageFileName
);
112 wxPNGReader::Create(int width
, int height
, int depth
, int colortype
)
114 Width
= width
; Height
= height
; Depth
= depth
;
115 ColorType
= (colortype
>=0) ? colortype
: ((Depth
>8) ? COLORTYPE_COLOR
: 0);
118 // GlobalFreePtr(lpbi);
123 lpbi
= 0; // TODO: wxDibCreate(Depth, Width, Height);
125 RawImage
= 0; //TODO: (ImagePointerType)wxDibPtr(lpbi);
126 EfeWidth
= (long)(((long)Width
*Depth
+ 31) / 32) * 4;
131 wxPNGReader::~wxPNGReader ( )
134 // TODO: GlobalFreePtr(lpbi);
140 int wxPNGReader::GetIndex(int x
, int y
)
142 if (!Inside(x
, y
) || (Depth
>8)) return -1;
144 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
145 int index
= (int)(*ImagePointer
);
149 bool wxPNGReader::GetRGB(int x
, int y
, byte
* r
, byte
* g
, byte
* b
)
151 if (!Inside(x
, y
)) return FALSE
;
154 return Palette
->GetRGB(GetIndex(x
, y
), r
, g
, b
);
155 /* PALETTEENTRY entry;
156 ::GetPaletteEntries((HPALETTE) Palette->GetHPALETTE(), GetIndex(x, y), 1, &entry);
159 *b = entry.peBlue; */
161 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
162 *b
= ImagePointer
[0];
163 *g
= ImagePointer
[1];
164 *r
= ImagePointer
[2];
170 bool wxPNGReader::SetIndex(int x
, int y
, int index
)
172 if (!Inside(x
, y
) || (Depth
>8)) return FALSE
;
174 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
175 *ImagePointer
= index
;
180 bool wxPNGReader::SetRGB(int x
, int y
, byte r
, byte g
, byte b
)
182 if (!Inside(x
, y
)) return FALSE
;
184 if (ColorType
& COLORTYPE_PALETTE
)
186 if (!Palette
) return FALSE
;
187 SetIndex(x
, y
, Palette
->GetPixel(r
, g
, b
));
190 ImagePointerType ImagePointer
= RawImage
+ EfeWidth
*y
+ (x
*Depth
>> 3);
199 bool wxPNGReader::SetPalette(wxPalette
* colourmap
)
203 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
205 // TODO: return (wxDibSetUsage(lpbi, (HPALETTE) Palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
210 wxPNGReader::SetPalette(int n
, byte
*r
, byte
*g
, byte
*b
)
212 Palette
= new wxPalette();
218 Palette
->Create(n
, r
, g
, b
);
219 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
220 // TODO: return (wxDibSetUsage(lpbi, (HPALETTE) Palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
225 wxPNGReader::SetPalette(int n
, rgb_color_struct
*rgb_struct
)
227 Palette
= new wxPalette();
231 byte r
[256], g
[256], b
[256];
233 for(int i
=0; i
<n
; i
++)
235 r
[i
] = rgb_struct
[i
].red
;
236 g
[i
] = rgb_struct
[i
].green
;
237 b
[i
] = rgb_struct
[i
].blue
;
239 // Added by JACS copying from Andrew Davison's additions
240 // to GIF-reading code
241 // Make transparency colour black...
243 r
[bgindex
] = g
[bgindex
] = b
[bgindex
] = 0;
245 Palette
->Create(n
, r
, g
, b
);
246 ColorType
|= (COLORTYPE_PALETTE
| COLORTYPE_COLOR
);
247 // TODO: return (wxDibSetUsage(lpbi, (HPALETTE) Palette->GetHPALETTE(), WXIMA_COLORS ) != 0);
251 void wxPNGReader::NullData()
257 wxBitmap
* wxPNGReader::GetBitmap()
259 wxBitmap
*bitmap
= new wxBitmap
;
260 if ( InstantiateBitmap(bitmap
) )
269 bool wxPNGReader::InstantiateBitmap(wxBitmap
*bitmap
)
273 HDC dc = ::CreateCompatibleDC(NULL);
277 // tmpBitmap is a dummy, to satisfy ::CreateCompatibleDC (it
278 // is a memory dc that must have a bitmap selected into it)
279 HDC dc2 = GetDC(NULL);
280 HBITMAP tmpBitmap = ::CreateCompatibleBitmap(dc2, GetWidth(), GetHeight());
281 ReleaseDC(NULL, dc2);
282 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, tmpBitmap);
286 ::SelectPalette(dc, (HPALETTE) Palette->GetHPALETTE(), FALSE);
287 ::RealizePalette(dc);
290 HBITMAP hBitmap = ::CreateDIBitmap(dc, lpbi,
291 CBM_INIT, RawImage, (LPBITMAPINFO) lpbi, DIB_PAL_COLORS);
293 ::SelectPalette(dc, NULL, TRUE);
294 ::SelectObject(dc, oldBitmap);
295 ::DeleteObject(tmpBitmap);
300 bitmap->SetHBITMAP((WXHBITMAP) hBitmap);
301 bitmap->SetWidth(GetWidth());
302 bitmap->SetHeight(GetHeight());
303 bitmap->SetDepth(GetDepth());
304 if ( GetDepth() > 1 && Palette )
305 bitmap->SetPalette(*Palette);
309 // Make a mask if appropriate
312 wxMask *mask = CreateMask();
313 bitmap->SetMask(mask);
330 wxPalette
*wxCopyPalette(const wxPalette
*cmap
)
332 // To get number of entries...
334 // TODO: ::GetObject((HPALETTE) cmap->GetHPALETTE(), sizeof(WORD), &count);
337 LOGPALETTE* logPal = (LOGPALETTE*)
338 new BYTE[sizeof(LOGPALETTE) + count*sizeof(PALETTEENTRY)];
339 logPal->palVersion = 0x300;
340 logPal->palNumEntries = count;
341 ::GetPaletteEntries((HPALETTE) cmap->GetHPALETTE(), 0, count, logPal->palPalEntry);
343 HPALETTE hPalette = ::CreatePalette(logPal);
346 wxPalette
*newCmap
= new wxPalette
;
347 // TODO: newCmap->SetHPALETTE((WXHPALETTE) hPalette);
351 wxMask
*wxPNGReader::CreateMask()
355 HBITMAP hBitmap = ::CreateBitmap(GetWidth(), GetHeight(), 1, 1, NULL);
357 HDC dc = ::CreateCompatibleDC(NULL);
358 HBITMAP oldBitmap = (HBITMAP) ::SelectObject(dc, hBitmap);
360 int bgIndex = GetBGIndex();
364 for (x=0; x<GetWidth(); x++)
366 for (y=0; y<GetHeight(); y++)
368 int index = GetIndex(x, y);
369 if ( index == bgIndex )
370 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(0, 0, 0));
372 ::SetPixel(dc, x, GetHeight() - y - 1, RGB(255, 255, 255));
376 ::SelectObject(dc, oldBitmap);
378 wxMask
*mask
= new wxMask
;
379 // TODO: mask->SetMaskBitmap((WXHBITMAP) hBitmap);
383 bool wxPNGReader::ReadFile(wxChar
* ImageFileName
)
386 wxStrcpy(filename
, ImageFileName
);
389 FILE *fp
= fopen(wxConvFile
.cWX2MB(filename
), "rb");
393 /* allocate the necessary structures */
394 png_struct
*png_ptr
= new (png_struct
);
401 png_info
*info_ptr
= new (png_info
);
409 /* set error handling */
410 if (setjmp(png_ptr
->jmpbuf
))
412 png_read_destroy(png_ptr
, info_ptr
, (png_info
*)0);
417 /* If we get here, we had a problem reading the file */
420 //png_set_error(ima_png_error, NULL);
422 /* initialize the structures, info first for error handling */
423 png_info_init(info_ptr
);
424 png_read_init(png_ptr
);
426 /* set up the input control */
427 png_init_io(png_ptr
, fp
);
429 /* read the file information */
430 png_read_info(png_ptr
, info_ptr
);
432 /* allocate the memory to hold the image using the fields
434 png_color_16 my_background
={ 0, 31, 127, 255, 0 };
436 if (info_ptr
->valid
& PNG_INFO_bKGD
)
438 png_set_background(png_ptr
, &(info_ptr
->background
),
439 PNG_BACKGROUND_GAMMA_FILE
, 1, 1.0);
440 if ( info_ptr
->num_palette
> 0 )
441 bgindex
= info_ptr
->background
.index
;
444 png_set_background(png_ptr
, &my_background
,
445 PNG_BACKGROUND_GAMMA_SCREEN
, 0, 1.0);
447 // Added by JACS: guesswork!
448 if ( info_ptr
->num_trans
!= 0 )
449 bgindex
= info_ptr
->num_trans
- 1 ;
452 /* tell libpng to strip 16 bit depth files down to 8 bits */
453 if (info_ptr
->bit_depth
== 16)
454 png_set_strip_16(png_ptr
);
456 int pixel_depth
=(info_ptr
->pixel_depth
<24) ? info_ptr
->pixel_depth
: 24;
457 Create(info_ptr
->width
, info_ptr
->height
, pixel_depth
,
458 info_ptr
->color_type
);
460 if (info_ptr
->num_palette
>0)
462 SetPalette((int)info_ptr
->num_palette
, (rgb_color_struct
*)info_ptr
->palette
);
465 int row_stride
= info_ptr
->width
* ((pixel_depth
+7)>>3);
466 // printf("P = %d D = %d RS= %d ", info_ptr->num_palette, info_ptr->pixel_depth,row_stride);
467 // printf("CT = %d TRS = %d BD= %d ", info_ptr->color_type, info_ptr->valid & PNG_INFO_tRNS,info_ptr->bit_depth);
469 byte
*row_pointers
= new byte
[row_stride
];
471 /* turn on interlace handling */
473 if (info_ptr
->interlace_type
)
474 number_passes
= png_set_interlace_handling(png_ptr
);
477 // printf("NP = %d ", number_passes);
479 // don't use the object to prevent warnings from VC++ about "unportable
480 // interaction between setjmp and C++ object destruction" (this is a correct
481 // warning, of course!)
482 wxPNGReaderIter
*iter
= new wxPNGReaderIter(this);
483 for (int pass
=0; pass
< number_passes
; pass
++)
488 //(unsigned char *)iter.GetRow();
489 if (info_ptr
->interlace_type
) {
491 iter
->GetRow(row_pointers
, row_stride
);
492 png_read_row(png_ptr
, row_pointers
, NULL
);
495 png_read_row(png_ptr
, row_pointers
, NULL
);
497 iter
->SetRow(row_pointers
, row_stride
);
499 } while(iter
->PrevRow());
500 // 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(wxChar
* ImageFileName
)
530 wxStrcpy(filename
, ImageFileName
);
532 wxPNGReaderIter
iter(this);
538 fp
= fopen(wxConvFile
.cWX2MB(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(wxChar
*filename
, wxChar
*name
)
699 wxStrcpy(nameStr
, name
);
702 wxStrcpy(nameStr
, filename
);
703 wxStripExtension(nameStr
);
706 if ( GetDepth() > 4 )
708 // Only a depth of 4 and below allowed
715 ofstream
str(wxConvFile
.cWX2MB(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/os2/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(WXSTRINGCAST name
))
774 return reader
.InstantiateBitmap(bitmap
);
780 bool wxPNGFileHandler::SaveFile(wxBitmap
*bitmap
, const wxString
& name
, int type
, const wxPalette
*pal
)