1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: samples/image/image.cpp
3 // Purpose: sample showing operations with wxImage
4 // Author: Robert Roebling
5 // Modified by: Francesco Montorsi
8 // Copyright: (c) 1998-2005 Robert Roebling
9 // License: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx/wx.h".
13 #include "wx/wxprec.h"
25 #include "wx/filename.h"
26 #include "wx/mstream.h"
27 #include "wx/wfstream.h"
28 #include "wx/quantize.h"
29 #include "wx/stopwatch.h"
32 #include "wx/dataobj.h"
33 #include "wx/clipbrd.h"
34 #endif // wxUSE_CLIPBOARD
36 #if defined(__WXMSW__)
37 #ifdef wxHAVE_RAW_BITMAP
38 #include "wx/rawbmp.h"
42 #if defined(__WXMAC__) || defined(__WXGTK__)
43 #define wxHAVE_RAW_BITMAP
44 #include "wx/rawbmp.h"
50 #include "../sample.xpm"
53 // ============================================================================
55 // ============================================================================
57 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
61 class MyApp
: public wxApp
64 virtual bool OnInit();
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
71 class MyFrame
: public wxFrame
76 void OnAbout( wxCommandEvent
&event
);
77 void OnNewFrame( wxCommandEvent
&event
);
78 void OnImageInfo( wxCommandEvent
&event
);
79 void OnThumbnail( wxCommandEvent
&event
);
81 #ifdef wxHAVE_RAW_BITMAP
82 void OnTestRawBitmap( wxCommandEvent
&event
);
83 #endif // wxHAVE_RAW_BITMAP
84 void OnQuit( wxCommandEvent
&event
);
87 void OnCopy(wxCommandEvent
& event
);
88 void OnPaste(wxCommandEvent
& event
);
89 #endif // wxUSE_CLIPBOARD
94 // ask user for the file name and try to load an image from it
96 // return the file path on success, empty string if we failed to load the
97 // image or were cancelled by user
98 static wxString
LoadUserImage(wxImage
& image
);
101 DECLARE_DYNAMIC_CLASS(MyFrame
)
102 DECLARE_EVENT_TABLE()
105 // ----------------------------------------------------------------------------
106 // Frame used for showing a standalone image
107 // ----------------------------------------------------------------------------
111 ID_ROTATE_LEFT
= wxID_HIGHEST
+1,
117 class MyImageFrame
: public wxFrame
120 MyImageFrame(wxFrame
*parent
, const wxString
& desc
, const wxBitmap
& bitmap
)
121 : wxFrame(parent
, wxID_ANY
,
122 wxString::Format(_T("Image from %s"), desc
.c_str()),
123 wxDefaultPosition
, wxDefaultSize
,
124 wxDEFAULT_FRAME_STYLE
| wxFULL_REPAINT_ON_RESIZE
),
127 wxMenu
*menu
= new wxMenu
;
128 menu
->Append(wxID_SAVE
);
129 menu
->AppendSeparator();
130 m_pClearBgMenu
= menu
->AppendCheckItem(ID_PAINT_BG
, _T("&Paint background"));
131 menu
->AppendSeparator();
132 menu
->Append(ID_RESIZE
, _T("&Fit to window\tCtrl-F"));
133 menu
->AppendSeparator();
134 menu
->Append(ID_ROTATE_LEFT
, _T("Rotate &left\tCtrl-L"));
135 menu
->Append(ID_ROTATE_RIGHT
, _T("Rotate &right\tCtrl-R"));
137 wxMenuBar
*mbar
= new wxMenuBar
;
138 mbar
->Append(menu
, _T("&Image"));
143 SetClientSize(bitmap
.GetWidth(), bitmap
.GetHeight());
147 // SetBackgroundColour(*wxWHITE);
150 void OnEraseBackground(wxEraseEvent
& WXUNUSED(event
))
152 // do nothing here to be able to see how transparent images are shown
155 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
159 if (m_pClearBgMenu
->IsChecked())
162 const wxSize size
= GetClientSize();
163 dc
.DrawBitmap(m_bitmap
,
164 (size
.x
- m_bitmap
.GetWidth())/2,
165 (size
.y
- m_bitmap
.GetHeight())/2,
166 true /* use mask */);
169 void OnSave(wxCommandEvent
& WXUNUSED(event
))
172 wxImage image
= m_bitmap
.ConvertToImage();
174 wxString savefilename
= wxFileSelector( wxT("Save Image"),
177 (const wxChar
*)NULL
,
178 wxT("BMP files (*.bmp)|*.bmp|")
179 wxT("PNG files (*.png)|*.png|")
180 wxT("JPEG files (*.jpg)|*.jpg|")
181 wxT("GIF files (*.gif)|*.gif|")
182 wxT("TIFF files (*.tif)|*.tif|")
183 wxT("PCX files (*.pcx)|*.pcx|")
184 wxT("ICO files (*.ico)|*.ico|")
185 wxT("CUR files (*.cur)|*.cur"),
189 if ( savefilename
.empty() )
193 wxFileName::SplitPath(savefilename
, NULL
, NULL
, &extension
);
196 if ( extension
== _T("bmp") )
198 static const int bppvalues
[] =
210 const wxString bppchoices
[] =
216 _T("8 bpp greyscale"),
218 _T("8 bpp own palette"),
222 int bppselection
= wxGetSingleChoiceIndex(_T("Set BMP BPP"),
223 _T("Image sample: save file"),
224 WXSIZEOF(bppchoices
),
227 if ( bppselection
!= -1 )
229 int format
= bppvalues
[bppselection
];
230 image
.SetOption(wxIMAGE_OPTION_BMP_FORMAT
, format
);
232 if ( format
== wxBMP_8BPP_PALETTE
)
234 unsigned char *cmap
= new unsigned char [256];
235 for ( int i
= 0; i
< 256; i
++ )
236 cmap
[i
] = (unsigned char)i
;
237 image
.SetPalette(wxPalette(256, cmap
, cmap
, cmap
));
243 else if ( extension
== _T("png") )
245 static const int pngvalues
[] =
255 const wxString pngchoices
[] =
262 _T("Grey red 16bpp"),
265 int sel
= wxGetSingleChoiceIndex(_T("Set PNG format"),
266 _T("Image sample: save file"),
267 WXSIZEOF(pngchoices
),
272 image
.SetOption(wxIMAGE_OPTION_PNG_FORMAT
, pngvalues
[sel
]);
273 image
.SetOption(wxIMAGE_OPTION_PNG_BITDEPTH
, sel
% 2 ? 16 : 8);
275 // these values are taken from OptiPNG with -o3 switch
276 const wxString compressionChoices
[] =
278 _T("compression = 9, memory = 8, strategy = 0, filter = 0"),
279 _T("compression = 9, memory = 9, strategy = 0, filter = 0"),
280 _T("compression = 9, memory = 8, strategy = 1, filter = 0"),
281 _T("compression = 9, memory = 9, strategy = 1, filter = 0"),
282 _T("compression = 1, memory = 8, strategy = 2, filter = 0"),
283 _T("compression = 1, memory = 9, strategy = 2, filter = 0"),
284 _T("compression = 9, memory = 8, strategy = 0, filter = 5"),
285 _T("compression = 9, memory = 9, strategy = 0, filter = 5"),
286 _T("compression = 9, memory = 8, strategy = 1, filter = 5"),
287 _T("compression = 9, memory = 9, strategy = 1, filter = 5"),
288 _T("compression = 1, memory = 8, strategy = 2, filter = 5"),
289 _T("compression = 1, memory = 9, strategy = 2, filter = 5"),
292 int sel
= wxGetSingleChoiceIndex(_T("Select compression option (Cancel to use default)\n"),
293 _T("PNG Compression Options"),
294 WXSIZEOF(compressionChoices
),
299 const int zc
[] = {9, 9, 9, 9, 1, 1, 9, 9, 9, 9, 1, 1};
300 const int zm
[] = {8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9};
301 const int zs
[] = {0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2};
302 const int f
[] = {0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
303 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8};
305 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL
, zc
[sel
]);
306 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL
, zm
[sel
]);
307 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY
, zs
[sel
]);
308 image
.SetOption(wxIMAGE_OPTION_PNG_FILTER
, f
[sel
]);
309 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE
, 1048576); // 1 MB
313 else if ( extension
== _T("cur") )
315 image
.Rescale(32,32);
316 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X
, 0);
317 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y
, 0);
318 // This shows how you can save an image with explicitly
319 // specified image format:
320 saved
= image
.SaveFile(savefilename
, wxBITMAP_TYPE_CUR
);
325 // This one guesses image format from filename extension
326 // (it may fail if the extension is not recognized):
327 image
.SaveFile(savefilename
);
329 #endif // wxUSE_FILEDLG
332 void OnResize(wxCommandEvent
& WXUNUSED(event
))
334 wxImage
img(m_bitmap
.ConvertToImage());
336 const wxSize size
= GetClientSize();
337 img
.Rescale(size
.x
, size
.y
, wxIMAGE_QUALITY_HIGH
);
338 m_bitmap
= wxBitmap(img
);
344 void OnRotate(wxCommandEvent
& event
)
347 if ( event
.GetId() == ID_ROTATE_LEFT
)
350 wxImage
img(m_bitmap
.ConvertToImage());
351 img
= img
.Rotate(angle
, wxPoint(img
.GetWidth() / 2, img
.GetHeight() / 2));
354 wxLogWarning(_T("Rotation failed"));
358 m_bitmap
= wxBitmap(img
);
365 void UpdateStatusBar()
367 wxLogStatus(this, _T("Image size: (%d, %d)"),
369 m_bitmap
.GetHeight());
373 wxMenuItem
* m_pClearBgMenu
;
375 DECLARE_EVENT_TABLE()
378 #ifdef wxHAVE_RAW_BITMAP
380 #include "wx/rawbmp.h"
382 class MyRawBitmapFrame
: public wxFrame
389 REAL_SIZE
= SIZE
- 2*BORDER
392 MyRawBitmapFrame(wxFrame
*parent
)
393 : wxFrame(parent
, wxID_ANY
, _T("Raw bitmaps (how exciting)")),
394 m_bitmap(SIZE
, SIZE
, 24),
395 m_alphaBitmap(SIZE
, SIZE
, 32)
397 SetClientSize(SIZE
, SIZE
*2+25);
404 void InitAlphaBitmap()
406 // First, clear the whole bitmap by making it alpha
408 wxAlphaPixelData
data( m_alphaBitmap
, wxPoint(0,0), wxSize(SIZE
, SIZE
) );
411 wxLogError(_T("Failed to gain raw access to bitmap data"));
414 wxAlphaPixelData::Iterator
p(data
);
415 for ( int y
= 0; y
< SIZE
; ++y
)
417 wxAlphaPixelData::Iterator rowStart
= p
;
418 for ( int x
= 0; x
< SIZE
; ++x
)
421 ++p
; // same as p.OffsetX(1)
428 // Then, draw colourful alpha-blended stripes
429 wxAlphaPixelData
data(m_alphaBitmap
, wxPoint(BORDER
, BORDER
),
430 wxSize(REAL_SIZE
, REAL_SIZE
));
433 wxLogError(_T("Failed to gain raw access to bitmap data"));
437 wxAlphaPixelData::Iterator
p(data
);
439 for ( int y
= 0; y
< REAL_SIZE
; ++y
)
441 wxAlphaPixelData::Iterator rowStart
= p
;
443 int r
= y
< REAL_SIZE
/3 ? 255 : 0,
444 g
= (REAL_SIZE
/3 <= y
) && (y
< 2*(REAL_SIZE
/3)) ? 255 : 0,
445 b
= 2*(REAL_SIZE
/3) <= y
? 255 : 0;
447 for ( int x
= 0; x
< REAL_SIZE
; ++x
)
449 // note that RGB must be premultiplied by alpha
450 unsigned a
= (wxAlphaPixelData::Iterator::ChannelType
)((x
*255.)/REAL_SIZE
);
451 p
.Red() = r
* a
/ 256;
452 p
.Green() = g
* a
/ 256;
453 p
.Blue() = b
* a
/ 256;
456 ++p
; // same as p.OffsetX(1)
466 // draw some colourful stripes without alpha
467 wxNativePixelData
data(m_bitmap
);
470 wxLogError(_T("Failed to gain raw access to bitmap data"));
474 wxNativePixelData::Iterator
p(data
);
475 for ( int y
= 0; y
< SIZE
; ++y
)
477 wxNativePixelData::Iterator rowStart
= p
;
479 int r
= y
< SIZE
/3 ? 255 : 0,
480 g
= (SIZE
/3 <= y
) && (y
< 2*(SIZE
/3)) ? 255 : 0,
481 b
= 2*(SIZE
/3) <= y
? 255 : 0;
483 for ( int x
= 0; x
< SIZE
; ++x
)
488 ++p
; // same as p.OffsetX(1)
496 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
498 wxPaintDC
dc( this );
499 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, BORDER
);
500 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
/2 - BORDER
);
501 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
- 2*BORDER
);
502 dc
.DrawBitmap( m_alphaBitmap
, 0, 0, true /* use mask */ );
504 dc
.DrawText(_T("Raw bitmap access without alpha"), 0, SIZE
+5);
505 dc
.DrawBitmap( m_bitmap
, 0, SIZE
+5+dc
.GetCharHeight());
510 wxBitmap m_alphaBitmap
;
512 DECLARE_EVENT_TABLE()
515 #endif // wxHAVE_RAW_BITMAP
518 // ============================================================================
520 // ============================================================================
522 //-----------------------------------------------------------------------------
524 //-----------------------------------------------------------------------------
526 BEGIN_EVENT_TABLE(MyImageFrame
, wxFrame
)
527 EVT_ERASE_BACKGROUND(MyImageFrame::OnEraseBackground
)
528 EVT_PAINT(MyImageFrame::OnPaint
)
530 EVT_MENU(wxID_SAVE
, MyImageFrame::OnSave
)
531 EVT_MENU_RANGE(ID_ROTATE_LEFT
, ID_ROTATE_RIGHT
, MyImageFrame::OnRotate
)
532 EVT_MENU(ID_RESIZE
, MyImageFrame::OnResize
)
535 //-----------------------------------------------------------------------------
537 //-----------------------------------------------------------------------------
539 #ifdef wxHAVE_RAW_BITMAP
541 BEGIN_EVENT_TABLE(MyRawBitmapFrame
, wxFrame
)
542 EVT_PAINT(MyRawBitmapFrame::OnPaint
)
545 #endif // wxHAVE_RAW_BITMAP
547 //-----------------------------------------------------------------------------
549 //-----------------------------------------------------------------------------
554 ID_ABOUT
= wxID_ABOUT
,
561 IMPLEMENT_DYNAMIC_CLASS( MyFrame
, wxFrame
)
562 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
563 EVT_MENU (ID_ABOUT
, MyFrame::OnAbout
)
564 EVT_MENU (ID_QUIT
, MyFrame::OnQuit
)
565 EVT_MENU (ID_NEW
, MyFrame::OnNewFrame
)
566 EVT_MENU (ID_INFO
, MyFrame::OnImageInfo
)
567 EVT_MENU (ID_SHOWTHUMBNAIL
, MyFrame::OnThumbnail
)
568 #ifdef wxHAVE_RAW_BITMAP
569 EVT_MENU (ID_SHOWRAW
, MyFrame::OnTestRawBitmap
)
572 EVT_MENU(wxID_COPY
, MyFrame::OnCopy
)
573 EVT_MENU(wxID_PASTE
, MyFrame::OnPaste
)
574 #endif // wxUSE_CLIPBOARD
578 : wxFrame( (wxFrame
*)NULL
, wxID_ANY
, _T("wxImage sample"),
579 wxPoint(20, 20), wxSize(950, 700) )
581 SetIcon(wxICON(sample
));
583 wxMenuBar
*menu_bar
= new wxMenuBar();
585 wxMenu
*menuImage
= new wxMenu
;
586 menuImage
->Append( ID_NEW
, _T("&Show any image...\tCtrl-O"));
587 menuImage
->Append( ID_INFO
, _T("Show image &information...\tCtrl-I"));
588 #ifdef wxHAVE_RAW_BITMAP
589 menuImage
->AppendSeparator();
590 menuImage
->Append( ID_SHOWRAW
, _T("Test &raw bitmap...\tCtrl-R"));
592 menuImage
->AppendSeparator();
593 menuImage
->Append( ID_SHOWTHUMBNAIL
, _T("Test &thumbnail...\tCtrl-T"),
594 "Test scaling the image during load (try with JPEG)");
595 menuImage
->AppendSeparator();
596 menuImage
->Append( ID_ABOUT
, _T("&About..."));
597 menuImage
->AppendSeparator();
598 menuImage
->Append( ID_QUIT
, _T("E&xit\tCtrl-Q"));
599 menu_bar
->Append(menuImage
, _T("&Image"));
602 wxMenu
*menuClipboard
= new wxMenu
;
603 menuClipboard
->Append(wxID_COPY
, _T("&Copy test image\tCtrl-C"));
604 menuClipboard
->Append(wxID_PASTE
, _T("&Paste image\tCtrl-V"));
605 menu_bar
->Append(menuClipboard
, _T("&Clipboard"));
606 #endif // wxUSE_CLIPBOARD
608 SetMenuBar( menu_bar
);
612 int widths
[] = { -1, 100 };
613 SetStatusWidths( 2, widths
);
614 #endif // wxUSE_STATUSBAR
616 m_canvas
= new MyCanvas( this, wxID_ANY
, wxPoint(0,0), wxSize(10,10) );
618 // 500 width * 2750 height
619 m_canvas
->SetScrollbars( 10, 10, 50, 275 );
622 void MyFrame::OnQuit( wxCommandEvent
&WXUNUSED(event
) )
627 void MyFrame::OnAbout( wxCommandEvent
&WXUNUSED(event
) )
629 (void)wxMessageBox( _T("wxImage demo\n")
630 _T("Robert Roebling (c) 1998,2000"),
631 _T("About wxImage Demo"), wxICON_INFORMATION
| wxOK
);
634 wxString
MyFrame::LoadUserImage(wxImage
& image
)
639 filename
= wxFileSelector(_T("Select image file"));
640 if ( !filename
.empty() )
642 if ( !image
.LoadFile(filename
) )
644 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
646 return wxEmptyString
;
649 #endif // wxUSE_FILEDLG
654 void MyFrame::OnNewFrame( wxCommandEvent
&WXUNUSED(event
) )
657 wxString filename
= LoadUserImage(image
);
658 if ( !filename
.empty() )
659 (new MyImageFrame(this, filename
, wxBitmap(image
)))->Show();
662 void MyFrame::OnImageInfo( wxCommandEvent
&WXUNUSED(event
) )
665 if ( !LoadUserImage(image
).empty() )
667 // TODO: show more information about the file
668 wxString info
= wxString::Format("Image size: %dx%d",
672 int xres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX
),
673 yres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY
);
676 info
+= wxString::Format("\nResolution: %dx%d", xres
, yres
);
677 switch ( image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT
) )
680 wxFAIL_MSG( "unknown image resolution units" );
683 case wxIMAGE_RESOLUTION_NONE
:
684 info
+= " in default units";
687 case wxIMAGE_RESOLUTION_INCHES
:
691 case wxIMAGE_RESOLUTION_CM
:
697 wxLogMessage("%s", info
);
701 #ifdef wxHAVE_RAW_BITMAP
703 void MyFrame::OnTestRawBitmap( wxCommandEvent
&WXUNUSED(event
) )
705 (new MyRawBitmapFrame(this))->Show();
708 #endif // wxHAVE_RAW_BITMAP
712 void MyFrame::OnCopy(wxCommandEvent
& WXUNUSED(event
))
714 wxBitmapDataObject
*dobjBmp
= new wxBitmapDataObject
;
715 dobjBmp
->SetBitmap(m_canvas
->my_horse_png
);
717 wxTheClipboard
->Open();
719 if ( !wxTheClipboard
->SetData(dobjBmp
) )
721 wxLogError(_T("Failed to copy bitmap to clipboard"));
724 wxTheClipboard
->Close();
727 void MyFrame::OnPaste(wxCommandEvent
& WXUNUSED(event
))
729 wxBitmapDataObject dobjBmp
;
731 wxTheClipboard
->Open();
732 if ( !wxTheClipboard
->GetData(dobjBmp
) )
734 wxLogMessage(_T("No bitmap data in the clipboard"));
738 (new MyImageFrame(this, _T("Clipboard"), dobjBmp
.GetBitmap()))->Show();
740 wxTheClipboard
->Close();
743 #endif // wxUSE_CLIPBOARD
745 void MyFrame::OnThumbnail( wxCommandEvent
&WXUNUSED(event
) )
748 wxString filename
= wxFileSelector(_T("Select image file"));
749 if ( filename
.empty() )
752 static const int THUMBNAIL_WIDTH
= 320;
753 static const int THUMBNAIL_HEIGHT
= 240;
756 image
.SetOption(wxIMAGE_OPTION_MAX_WIDTH
, THUMBNAIL_WIDTH
);
757 image
.SetOption(wxIMAGE_OPTION_MAX_HEIGHT
, THUMBNAIL_HEIGHT
);
760 if ( !image
.LoadFile(filename
) )
762 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
766 const long loadTime
= sw
.Time();
769 frame
= new MyImageFrame(this, filename
, wxBitmap(image
));
771 wxLogStatus(frame
, "Loaded \"%s\" in %ldms", filename
, loadTime
);
773 wxLogError( _T("Couldn't create file selector dialog") );
775 #endif // wxUSE_FILEDLG
778 //-----------------------------------------------------------------------------
780 //-----------------------------------------------------------------------------
786 if ( !wxApp::OnInit() )
789 wxInitAllImageHandlers();
791 wxFrame
*frame
= new MyFrame();