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 // ============================================================================
52 // ============================================================================
54 //-----------------------------------------------------------------------------
56 //-----------------------------------------------------------------------------
58 class MyApp
: public wxApp
61 virtual bool OnInit();
64 // ----------------------------------------------------------------------------
66 // ----------------------------------------------------------------------------
68 class MyFrame
: public wxFrame
73 void OnAbout( wxCommandEvent
&event
);
74 void OnNewFrame( wxCommandEvent
&event
);
75 void OnImageInfo( wxCommandEvent
&event
);
76 void OnThumbnail( wxCommandEvent
&event
);
78 #ifdef wxHAVE_RAW_BITMAP
79 void OnTestRawBitmap( wxCommandEvent
&event
);
80 #endif // wxHAVE_RAW_BITMAP
81 void OnQuit( wxCommandEvent
&event
);
84 void OnCopy(wxCommandEvent
& event
);
85 void OnPaste(wxCommandEvent
& event
);
86 #endif // wxUSE_CLIPBOARD
91 // ask user for the file name and try to load an image from it
93 // return the file path on success, empty string if we failed to load the
94 // image or were cancelled by user
95 static wxString
LoadUserImage(wxImage
& image
);
98 DECLARE_DYNAMIC_CLASS(MyFrame
)
102 // ----------------------------------------------------------------------------
103 // Frame used for showing a standalone image
104 // ----------------------------------------------------------------------------
108 ID_ROTATE_LEFT
= wxID_HIGHEST
+1,
114 class MyImageFrame
: public wxFrame
117 MyImageFrame(wxFrame
*parent
, const wxString
& desc
, const wxBitmap
& bitmap
)
118 : wxFrame(parent
, wxID_ANY
,
119 wxString::Format(_T("Image from %s"), desc
.c_str()),
120 wxDefaultPosition
, wxDefaultSize
,
121 wxDEFAULT_FRAME_STYLE
| wxFULL_REPAINT_ON_RESIZE
),
124 wxMenu
*menu
= new wxMenu
;
125 menu
->Append(wxID_SAVE
);
126 menu
->AppendSeparator();
127 m_pClearBgMenu
= menu
->AppendCheckItem(ID_PAINT_BG
, _T("&Paint background"));
128 menu
->AppendSeparator();
129 menu
->Append(ID_RESIZE
, _T("&Fit to window\tCtrl-F"));
130 menu
->AppendSeparator();
131 menu
->Append(ID_ROTATE_LEFT
, _T("Rotate &left\tCtrl-L"));
132 menu
->Append(ID_ROTATE_RIGHT
, _T("Rotate &right\tCtrl-R"));
134 wxMenuBar
*mbar
= new wxMenuBar
;
135 mbar
->Append(menu
, _T("&Image"));
140 SetClientSize(bitmap
.GetWidth(), bitmap
.GetHeight());
144 // SetBackgroundColour(*wxWHITE);
147 void OnEraseBackground(wxEraseEvent
& WXUNUSED(event
))
149 // do nothing here to be able to see how transparent images are shown
152 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
156 if (m_pClearBgMenu
->IsChecked())
159 const wxSize size
= GetClientSize();
160 dc
.DrawBitmap(m_bitmap
,
161 (size
.x
- m_bitmap
.GetWidth())/2,
162 (size
.y
- m_bitmap
.GetHeight())/2,
163 true /* use mask */);
166 void OnSave(wxCommandEvent
& WXUNUSED(event
))
169 wxImage image
= m_bitmap
.ConvertToImage();
171 wxString savefilename
= wxFileSelector( wxT("Save Image"),
174 (const wxChar
*)NULL
,
175 wxT("BMP files (*.bmp)|*.bmp|")
176 wxT("PNG files (*.png)|*.png|")
177 wxT("JPEG files (*.jpg)|*.jpg|")
178 wxT("GIF files (*.gif)|*.gif|")
179 wxT("TIFF files (*.tif)|*.tif|")
180 wxT("PCX files (*.pcx)|*.pcx|")
181 wxT("ICO files (*.ico)|*.ico|")
182 wxT("CUR files (*.cur)|*.cur"),
186 if ( savefilename
.empty() )
190 wxFileName::SplitPath(savefilename
, NULL
, NULL
, &extension
);
193 if ( extension
== _T("bmp") )
195 static const int bppvalues
[] =
207 const wxString bppchoices
[] =
213 _T("8 bpp greyscale"),
215 _T("8 bpp own palette"),
219 int bppselection
= wxGetSingleChoiceIndex(_T("Set BMP BPP"),
220 _T("Image sample: save file"),
221 WXSIZEOF(bppchoices
),
224 if ( bppselection
!= -1 )
226 int format
= bppvalues
[bppselection
];
227 image
.SetOption(wxIMAGE_OPTION_BMP_FORMAT
, format
);
229 if ( format
== wxBMP_8BPP_PALETTE
)
231 unsigned char *cmap
= new unsigned char [256];
232 for ( int i
= 0; i
< 256; i
++ )
233 cmap
[i
] = (unsigned char)i
;
234 image
.SetPalette(wxPalette(256, cmap
, cmap
, cmap
));
240 else if ( extension
== _T("png") )
242 static const int pngvalues
[] =
252 const wxString pngchoices
[] =
259 _T("Grey red 16bpp"),
262 int sel
= wxGetSingleChoiceIndex(_T("Set PNG format"),
263 _T("Image sample: save file"),
264 WXSIZEOF(pngchoices
),
269 image
.SetOption(wxIMAGE_OPTION_PNG_FORMAT
, pngvalues
[sel
]);
270 image
.SetOption(wxIMAGE_OPTION_PNG_BITDEPTH
, sel
% 2 ? 16 : 8);
272 // these values are taken from OptiPNG with -o3 switch
273 const wxString compressionChoices
[] =
275 _T("compression = 9, memory = 8, strategy = 0, filter = 0"),
276 _T("compression = 9, memory = 9, strategy = 0, filter = 0"),
277 _T("compression = 9, memory = 8, strategy = 1, filter = 0"),
278 _T("compression = 9, memory = 9, strategy = 1, filter = 0"),
279 _T("compression = 1, memory = 8, strategy = 2, filter = 0"),
280 _T("compression = 1, memory = 9, strategy = 2, filter = 0"),
281 _T("compression = 9, memory = 8, strategy = 0, filter = 5"),
282 _T("compression = 9, memory = 9, strategy = 0, filter = 5"),
283 _T("compression = 9, memory = 8, strategy = 1, filter = 5"),
284 _T("compression = 9, memory = 9, strategy = 1, filter = 5"),
285 _T("compression = 1, memory = 8, strategy = 2, filter = 5"),
286 _T("compression = 1, memory = 9, strategy = 2, filter = 5"),
289 int sel
= wxGetSingleChoiceIndex(_T("Select compression option (Cancel to use default)\n"),
290 _T("PNG Compression Options"),
291 WXSIZEOF(compressionChoices
),
296 const int zc
[] = {9, 9, 9, 9, 1, 1, 9, 9, 9, 9, 1, 1};
297 const int zm
[] = {8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9};
298 const int zs
[] = {0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2};
299 const int f
[] = {0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
300 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8};
302 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL
, zc
[sel
]);
303 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL
, zm
[sel
]);
304 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY
, zs
[sel
]);
305 image
.SetOption(wxIMAGE_OPTION_PNG_FILTER
, f
[sel
]);
306 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE
, 1048576); // 1 MB
310 else if ( extension
== _T("cur") )
312 image
.Rescale(32,32);
313 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X
, 0);
314 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y
, 0);
315 // This shows how you can save an image with explicitly
316 // specified image format:
317 saved
= image
.SaveFile(savefilename
, wxBITMAP_TYPE_CUR
);
322 // This one guesses image format from filename extension
323 // (it may fail if the extension is not recognized):
324 image
.SaveFile(savefilename
);
326 #endif // wxUSE_FILEDLG
329 void OnResize(wxCommandEvent
& WXUNUSED(event
))
331 wxImage
img(m_bitmap
.ConvertToImage());
333 const wxSize size
= GetClientSize();
334 img
.Rescale(size
.x
, size
.y
, wxIMAGE_QUALITY_HIGH
);
335 m_bitmap
= wxBitmap(img
);
341 void OnRotate(wxCommandEvent
& event
)
344 if ( event
.GetId() == ID_ROTATE_LEFT
)
347 wxImage
img(m_bitmap
.ConvertToImage());
348 img
= img
.Rotate(angle
, wxPoint(img
.GetWidth() / 2, img
.GetHeight() / 2));
351 wxLogWarning(_T("Rotation failed"));
355 m_bitmap
= wxBitmap(img
);
362 void UpdateStatusBar()
364 wxLogStatus(this, _T("Image size: (%d, %d)"),
366 m_bitmap
.GetHeight());
370 wxMenuItem
* m_pClearBgMenu
;
372 DECLARE_EVENT_TABLE()
375 #ifdef wxHAVE_RAW_BITMAP
377 #include "wx/rawbmp.h"
379 class MyRawBitmapFrame
: public wxFrame
386 REAL_SIZE
= SIZE
- 2*BORDER
389 MyRawBitmapFrame(wxFrame
*parent
)
390 : wxFrame(parent
, wxID_ANY
, _T("Raw bitmaps (how exciting)")),
391 m_bitmap(SIZE
, SIZE
, 24),
392 m_alphaBitmap(SIZE
, SIZE
, 32)
394 SetClientSize(SIZE
, SIZE
*2+25);
401 void InitAlphaBitmap()
403 // First, clear the whole bitmap by making it alpha
405 wxAlphaPixelData
data( m_alphaBitmap
, wxPoint(0,0), wxSize(SIZE
, SIZE
) );
408 wxLogError(_T("Failed to gain raw access to bitmap data"));
411 wxAlphaPixelData::Iterator
p(data
);
412 for ( int y
= 0; y
< SIZE
; ++y
)
414 wxAlphaPixelData::Iterator rowStart
= p
;
415 for ( int x
= 0; x
< SIZE
; ++x
)
418 ++p
; // same as p.OffsetX(1)
425 // Then, draw colourful alpha-blended stripes
426 wxAlphaPixelData
data(m_alphaBitmap
, wxPoint(BORDER
, BORDER
),
427 wxSize(REAL_SIZE
, REAL_SIZE
));
430 wxLogError(_T("Failed to gain raw access to bitmap data"));
434 wxAlphaPixelData::Iterator
p(data
);
436 for ( int y
= 0; y
< REAL_SIZE
; ++y
)
438 wxAlphaPixelData::Iterator rowStart
= p
;
440 int r
= y
< REAL_SIZE
/3 ? 255 : 0,
441 g
= (REAL_SIZE
/3 <= y
) && (y
< 2*(REAL_SIZE
/3)) ? 255 : 0,
442 b
= 2*(REAL_SIZE
/3) <= y
? 255 : 0;
444 for ( int x
= 0; x
< REAL_SIZE
; ++x
)
446 // note that RGB must be premultiplied by alpha
447 unsigned a
= (wxAlphaPixelData::Iterator::ChannelType
)((x
*255.)/REAL_SIZE
);
448 p
.Red() = r
* a
/ 256;
449 p
.Green() = g
* a
/ 256;
450 p
.Blue() = b
* a
/ 256;
453 ++p
; // same as p.OffsetX(1)
463 // draw some colourful stripes without alpha
464 wxNativePixelData
data(m_bitmap
);
467 wxLogError(_T("Failed to gain raw access to bitmap data"));
471 wxNativePixelData::Iterator
p(data
);
472 for ( int y
= 0; y
< SIZE
; ++y
)
474 wxNativePixelData::Iterator rowStart
= p
;
476 int r
= y
< SIZE
/3 ? 255 : 0,
477 g
= (SIZE
/3 <= y
) && (y
< 2*(SIZE
/3)) ? 255 : 0,
478 b
= 2*(SIZE
/3) <= y
? 255 : 0;
480 for ( int x
= 0; x
< SIZE
; ++x
)
485 ++p
; // same as p.OffsetX(1)
493 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
495 wxPaintDC
dc( this );
496 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, BORDER
);
497 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
/2 - BORDER
);
498 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
- 2*BORDER
);
499 dc
.DrawBitmap( m_alphaBitmap
, 0, 0, true /* use mask */ );
501 dc
.DrawText(_T("Raw bitmap access without alpha"), 0, SIZE
+5);
502 dc
.DrawBitmap( m_bitmap
, 0, SIZE
+5+dc
.GetCharHeight());
507 wxBitmap m_alphaBitmap
;
509 DECLARE_EVENT_TABLE()
512 #endif // wxHAVE_RAW_BITMAP
515 // ============================================================================
517 // ============================================================================
519 //-----------------------------------------------------------------------------
521 //-----------------------------------------------------------------------------
523 BEGIN_EVENT_TABLE(MyImageFrame
, wxFrame
)
524 EVT_ERASE_BACKGROUND(MyImageFrame::OnEraseBackground
)
525 EVT_PAINT(MyImageFrame::OnPaint
)
527 EVT_MENU(wxID_SAVE
, MyImageFrame::OnSave
)
528 EVT_MENU_RANGE(ID_ROTATE_LEFT
, ID_ROTATE_RIGHT
, MyImageFrame::OnRotate
)
529 EVT_MENU(ID_RESIZE
, MyImageFrame::OnResize
)
532 //-----------------------------------------------------------------------------
534 //-----------------------------------------------------------------------------
536 #ifdef wxHAVE_RAW_BITMAP
538 BEGIN_EVENT_TABLE(MyRawBitmapFrame
, wxFrame
)
539 EVT_PAINT(MyRawBitmapFrame::OnPaint
)
542 #endif // wxHAVE_RAW_BITMAP
544 //-----------------------------------------------------------------------------
546 //-----------------------------------------------------------------------------
551 ID_ABOUT
= wxID_ABOUT
,
558 IMPLEMENT_DYNAMIC_CLASS( MyFrame
, wxFrame
)
559 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
560 EVT_MENU (ID_ABOUT
, MyFrame::OnAbout
)
561 EVT_MENU (ID_QUIT
, MyFrame::OnQuit
)
562 EVT_MENU (ID_NEW
, MyFrame::OnNewFrame
)
563 EVT_MENU (ID_INFO
, MyFrame::OnImageInfo
)
564 EVT_MENU (ID_SHOWTHUMBNAIL
, MyFrame::OnThumbnail
)
565 #ifdef wxHAVE_RAW_BITMAP
566 EVT_MENU (ID_SHOWRAW
, MyFrame::OnTestRawBitmap
)
569 EVT_MENU(wxID_COPY
, MyFrame::OnCopy
)
570 EVT_MENU(wxID_PASTE
, MyFrame::OnPaste
)
571 #endif // wxUSE_CLIPBOARD
575 : wxFrame( (wxFrame
*)NULL
, wxID_ANY
, _T("wxImage sample"),
576 wxPoint(20, 20), wxSize(950, 700) )
578 wxMenuBar
*menu_bar
= new wxMenuBar();
580 wxMenu
*menuImage
= new wxMenu
;
581 menuImage
->Append( ID_NEW
, _T("&Show any image...\tCtrl-O"));
582 menuImage
->Append( ID_INFO
, _T("Show image &information...\tCtrl-I"));
583 #ifdef wxHAVE_RAW_BITMAP
584 menuImage
->AppendSeparator();
585 menuImage
->Append( ID_SHOWRAW
, _T("Test &raw bitmap...\tCtrl-R"));
587 menuImage
->AppendSeparator();
588 menuImage
->Append( ID_SHOWTHUMBNAIL
, _T("Test &thumbnail...\tCtrl-T"),
589 "Test scaling the image during load (try with JPEG)");
590 menuImage
->AppendSeparator();
591 menuImage
->Append( ID_ABOUT
, _T("&About..."));
592 menuImage
->AppendSeparator();
593 menuImage
->Append( ID_QUIT
, _T("E&xit\tCtrl-Q"));
594 menu_bar
->Append(menuImage
, _T("&Image"));
597 wxMenu
*menuClipboard
= new wxMenu
;
598 menuClipboard
->Append(wxID_COPY
, _T("&Copy test image\tCtrl-C"));
599 menuClipboard
->Append(wxID_PASTE
, _T("&Paste image\tCtrl-V"));
600 menu_bar
->Append(menuClipboard
, _T("&Clipboard"));
601 #endif // wxUSE_CLIPBOARD
603 SetMenuBar( menu_bar
);
607 int widths
[] = { -1, 100 };
608 SetStatusWidths( 2, widths
);
609 #endif // wxUSE_STATUSBAR
611 m_canvas
= new MyCanvas( this, wxID_ANY
, wxPoint(0,0), wxSize(10,10) );
613 // 500 width * 2750 height
614 m_canvas
->SetScrollbars( 10, 10, 50, 275 );
617 void MyFrame::OnQuit( wxCommandEvent
&WXUNUSED(event
) )
622 void MyFrame::OnAbout( wxCommandEvent
&WXUNUSED(event
) )
624 (void)wxMessageBox( _T("wxImage demo\n")
625 _T("Robert Roebling (c) 1998,2000"),
626 _T("About wxImage Demo"), wxICON_INFORMATION
| wxOK
);
629 wxString
MyFrame::LoadUserImage(wxImage
& image
)
634 filename
= wxFileSelector(_T("Select image file"));
635 if ( !filename
.empty() )
637 if ( !image
.LoadFile(filename
) )
639 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
641 return wxEmptyString
;
644 #endif // wxUSE_FILEDLG
649 void MyFrame::OnNewFrame( wxCommandEvent
&WXUNUSED(event
) )
652 wxString filename
= LoadUserImage(image
);
653 if ( !filename
.empty() )
654 (new MyImageFrame(this, filename
, wxBitmap(image
)))->Show();
657 void MyFrame::OnImageInfo( wxCommandEvent
&WXUNUSED(event
) )
660 if ( !LoadUserImage(image
).empty() )
662 // TODO: show more information about the file
663 wxString info
= wxString::Format("Image size: %dx%d",
667 int xres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX
),
668 yres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY
);
671 info
+= wxString::Format("\nResolution: %dx%d", xres
, yres
);
672 switch ( image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT
) )
675 wxFAIL_MSG( "unknown image resolution units" );
678 case wxIMAGE_RESOLUTION_NONE
:
679 info
+= " in default units";
682 case wxIMAGE_RESOLUTION_INCHES
:
686 case wxIMAGE_RESOLUTION_CM
:
692 wxLogMessage("%s", info
);
696 #ifdef wxHAVE_RAW_BITMAP
698 void MyFrame::OnTestRawBitmap( wxCommandEvent
&WXUNUSED(event
) )
700 (new MyRawBitmapFrame(this))->Show();
703 #endif // wxHAVE_RAW_BITMAP
707 void MyFrame::OnCopy(wxCommandEvent
& WXUNUSED(event
))
709 wxBitmapDataObject
*dobjBmp
= new wxBitmapDataObject
;
710 dobjBmp
->SetBitmap(m_canvas
->my_horse_png
);
712 wxTheClipboard
->Open();
714 if ( !wxTheClipboard
->SetData(dobjBmp
) )
716 wxLogError(_T("Failed to copy bitmap to clipboard"));
719 wxTheClipboard
->Close();
722 void MyFrame::OnPaste(wxCommandEvent
& WXUNUSED(event
))
724 wxBitmapDataObject dobjBmp
;
726 wxTheClipboard
->Open();
727 if ( !wxTheClipboard
->GetData(dobjBmp
) )
729 wxLogMessage(_T("No bitmap data in the clipboard"));
733 (new MyImageFrame(this, _T("Clipboard"), dobjBmp
.GetBitmap()))->Show();
735 wxTheClipboard
->Close();
738 #endif // wxUSE_CLIPBOARD
740 void MyFrame::OnThumbnail( wxCommandEvent
&WXUNUSED(event
) )
743 wxString filename
= wxFileSelector(_T("Select image file"));
744 if ( filename
.empty() )
747 static const int THUMBNAIL_WIDTH
= 320;
748 static const int THUMBNAIL_HEIGHT
= 240;
751 image
.SetOption(wxIMAGE_OPTION_MAX_WIDTH
, THUMBNAIL_WIDTH
);
752 image
.SetOption(wxIMAGE_OPTION_MAX_HEIGHT
, THUMBNAIL_HEIGHT
);
755 if ( !image
.LoadFile(filename
) )
757 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
761 const long loadTime
= sw
.Time();
764 frame
= new MyImageFrame(this, filename
, wxBitmap(image
));
766 wxLogStatus(frame
, "Loaded \"%s\" in %ldms", filename
, loadTime
);
768 wxLogError( _T("Couldn't create file selector dialog") );
770 #endif // wxUSE_FILEDLG
773 //-----------------------------------------------------------------------------
775 //-----------------------------------------------------------------------------
781 if ( !wxApp::OnInit() )
784 wxInitAllImageHandlers();
786 wxFrame
*frame
= new MyFrame();