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);
273 else if ( extension
== _T("cur") )
275 image
.Rescale(32,32);
276 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X
, 0);
277 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y
, 0);
278 // This shows how you can save an image with explicitly
279 // specified image format:
280 saved
= image
.SaveFile(savefilename
, wxBITMAP_TYPE_CUR
);
285 // This one guesses image format from filename extension
286 // (it may fail if the extension is not recognized):
287 image
.SaveFile(savefilename
);
289 #endif // wxUSE_FILEDLG
292 void OnResize(wxCommandEvent
& WXUNUSED(event
))
294 wxImage
img(m_bitmap
.ConvertToImage());
296 const wxSize size
= GetClientSize();
297 img
.Rescale(size
.x
, size
.y
, wxIMAGE_QUALITY_HIGH
);
298 m_bitmap
= wxBitmap(img
);
304 void OnRotate(wxCommandEvent
& event
)
307 if ( event
.GetId() == ID_ROTATE_LEFT
)
310 wxImage
img(m_bitmap
.ConvertToImage());
311 img
= img
.Rotate(angle
, wxPoint(img
.GetWidth() / 2, img
.GetHeight() / 2));
314 wxLogWarning(_T("Rotation failed"));
318 m_bitmap
= wxBitmap(img
);
325 void UpdateStatusBar()
327 wxLogStatus(this, _T("Image size: (%d, %d)"),
329 m_bitmap
.GetHeight());
333 wxMenuItem
* m_pClearBgMenu
;
335 DECLARE_EVENT_TABLE()
338 #ifdef wxHAVE_RAW_BITMAP
340 #include "wx/rawbmp.h"
342 class MyRawBitmapFrame
: public wxFrame
349 REAL_SIZE
= SIZE
- 2*BORDER
352 MyRawBitmapFrame(wxFrame
*parent
)
353 : wxFrame(parent
, wxID_ANY
, _T("Raw bitmaps (how exciting)")),
354 m_bitmap(SIZE
, SIZE
, 24),
355 m_alphaBitmap(SIZE
, SIZE
, 32)
357 SetClientSize(SIZE
, SIZE
*2+25);
364 void InitAlphaBitmap()
366 // First, clear the whole bitmap by making it alpha
368 wxAlphaPixelData
data( m_alphaBitmap
, wxPoint(0,0), wxSize(SIZE
, SIZE
) );
371 wxLogError(_T("Failed to gain raw access to bitmap data"));
374 wxAlphaPixelData
::Iterator
p(data
);
375 for ( int y
= 0; y
< SIZE
; ++y
)
377 wxAlphaPixelData
::Iterator rowStart
= p
;
378 for ( int x
= 0; x
< SIZE
; ++x
)
381 ++p
; // same as p.OffsetX(1)
388 // Then, draw colourful alpha-blended stripes
389 wxAlphaPixelData
data(m_alphaBitmap
, wxPoint(BORDER
, BORDER
),
390 wxSize(REAL_SIZE
, REAL_SIZE
));
393 wxLogError(_T("Failed to gain raw access to bitmap data"));
397 wxAlphaPixelData
::Iterator
p(data
);
399 for ( int y
= 0; y
< REAL_SIZE
; ++y
)
401 wxAlphaPixelData
::Iterator rowStart
= p
;
403 int r
= y
< REAL_SIZE
/3 ?
255 : 0,
404 g
= (REAL_SIZE
/3 <= y
) && (y
< 2*(REAL_SIZE
/3)) ?
255 : 0,
405 b
= 2*(REAL_SIZE
/3) <= y ?
255 : 0;
407 for ( int x
= 0; x
< REAL_SIZE
; ++x
)
409 // note that RGB must be premultiplied by alpha
410 unsigned a
= (wxAlphaPixelData
::Iterator
::ChannelType
)((x
*255.)/REAL_SIZE
);
411 p
.Red() = r
* a
/ 256;
412 p
.Green() = g
* a
/ 256;
413 p
.Blue() = b
* a
/ 256;
416 ++p
; // same as p.OffsetX(1)
426 // draw some colourful stripes without alpha
427 wxNativePixelData
data(m_bitmap
);
430 wxLogError(_T("Failed to gain raw access to bitmap data"));
434 wxNativePixelData
::Iterator
p(data
);
435 for ( int y
= 0; y
< SIZE
; ++y
)
437 wxNativePixelData
::Iterator rowStart
= p
;
439 int r
= y
< SIZE
/3 ?
255 : 0,
440 g
= (SIZE
/3 <= y
) && (y
< 2*(SIZE
/3)) ?
255 : 0,
441 b
= 2*(SIZE
/3) <= y ?
255 : 0;
443 for ( int x
= 0; x
< SIZE
; ++x
)
448 ++p
; // same as p.OffsetX(1)
456 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
458 wxPaintDC
dc( this );
459 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, BORDER
);
460 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
/2 - BORDER
);
461 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
- 2*BORDER
);
462 dc
.DrawBitmap( m_alphaBitmap
, 0, 0, true /* use mask */ );
464 dc
.DrawText(_T("Raw bitmap access without alpha"), 0, SIZE
+5);
465 dc
.DrawBitmap( m_bitmap
, 0, SIZE
+5+dc
.GetCharHeight());
470 wxBitmap m_alphaBitmap
;
472 DECLARE_EVENT_TABLE()
475 #endif // wxHAVE_RAW_BITMAP
478 // ============================================================================
480 // ============================================================================
482 //-----------------------------------------------------------------------------
484 //-----------------------------------------------------------------------------
486 BEGIN_EVENT_TABLE(MyImageFrame
, wxFrame
)
487 EVT_ERASE_BACKGROUND(MyImageFrame
::OnEraseBackground
)
488 EVT_PAINT(MyImageFrame
::OnPaint
)
490 EVT_MENU(wxID_SAVE
, MyImageFrame
::OnSave
)
491 EVT_MENU_RANGE(ID_ROTATE_LEFT
, ID_ROTATE_RIGHT
, MyImageFrame
::OnRotate
)
492 EVT_MENU(ID_RESIZE
, MyImageFrame
::OnResize
)
495 //-----------------------------------------------------------------------------
497 //-----------------------------------------------------------------------------
499 #ifdef wxHAVE_RAW_BITMAP
501 BEGIN_EVENT_TABLE(MyRawBitmapFrame
, wxFrame
)
502 EVT_PAINT(MyRawBitmapFrame
::OnPaint
)
505 #endif // wxHAVE_RAW_BITMAP
507 //-----------------------------------------------------------------------------
509 //-----------------------------------------------------------------------------
514 ID_ABOUT
= wxID_ABOUT
,
521 IMPLEMENT_DYNAMIC_CLASS( MyFrame
, wxFrame
)
522 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
523 EVT_MENU (ID_ABOUT
, MyFrame
::OnAbout
)
524 EVT_MENU (ID_QUIT
, MyFrame
::OnQuit
)
525 EVT_MENU (ID_NEW
, MyFrame
::OnNewFrame
)
526 EVT_MENU (ID_INFO
, MyFrame
::OnImageInfo
)
527 EVT_MENU (ID_SHOWTHUMBNAIL
, MyFrame
::OnThumbnail
)
528 #ifdef wxHAVE_RAW_BITMAP
529 EVT_MENU (ID_SHOWRAW
, MyFrame
::OnTestRawBitmap
)
532 EVT_MENU(wxID_COPY
, MyFrame
::OnCopy
)
533 EVT_MENU(wxID_PASTE
, MyFrame
::OnPaste
)
534 #endif // wxUSE_CLIPBOARD
538 : wxFrame( (wxFrame
*)NULL
, wxID_ANY
, _T("wxImage sample"),
539 wxPoint(20, 20), wxSize(950, 700) )
541 wxMenuBar
*menu_bar
= new wxMenuBar();
543 wxMenu
*menuImage
= new wxMenu
;
544 menuImage
->Append( ID_NEW
, _T("&Show any image...\tCtrl-O"));
545 menuImage
->Append( ID_INFO
, _T("Show image &information...\tCtrl-I"));
546 #ifdef wxHAVE_RAW_BITMAP
547 menuImage
->AppendSeparator();
548 menuImage
->Append( ID_SHOWRAW
, _T("Test &raw bitmap...\tCtrl-R"));
550 menuImage
->AppendSeparator();
551 menuImage
->Append( ID_SHOWTHUMBNAIL
, _T("Test &thumbnail...\tCtrl-T"),
552 "Test scaling the image during load (try with JPEG)");
553 menuImage
->AppendSeparator();
554 menuImage
->Append( ID_ABOUT
, _T("&About..."));
555 menuImage
->AppendSeparator();
556 menuImage
->Append( ID_QUIT
, _T("E&xit\tCtrl-Q"));
557 menu_bar
->Append(menuImage
, _T("&Image"));
560 wxMenu
*menuClipboard
= new wxMenu
;
561 menuClipboard
->Append(wxID_COPY
, _T("&Copy test image\tCtrl-C"));
562 menuClipboard
->Append(wxID_PASTE
, _T("&Paste image\tCtrl-V"));
563 menu_bar
->Append(menuClipboard
, _T("&Clipboard"));
564 #endif // wxUSE_CLIPBOARD
566 SetMenuBar( menu_bar
);
570 int widths
[] = { -1, 100 };
571 SetStatusWidths( 2, widths
);
572 #endif // wxUSE_STATUSBAR
574 m_canvas
= new MyCanvas( this, wxID_ANY
, wxPoint(0,0), wxSize(10,10) );
576 // 500 width * 2750 height
577 m_canvas
->SetScrollbars( 10, 10, 50, 275 );
580 void MyFrame
::OnQuit( wxCommandEvent
&WXUNUSED(event
) )
585 void MyFrame
::OnAbout( wxCommandEvent
&WXUNUSED(event
) )
587 (void)wxMessageBox( _T("wxImage demo\n")
588 _T("Robert Roebling (c) 1998,2000"),
589 _T("About wxImage Demo"), wxICON_INFORMATION
| wxOK
);
592 wxString MyFrame
::LoadUserImage(wxImage
& image
)
597 filename
= wxFileSelector(_T("Select image file"));
598 if ( !filename
.empty() )
600 if ( !image
.LoadFile(filename
) )
602 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
604 return wxEmptyString
;
607 #endif // wxUSE_FILEDLG
612 void MyFrame
::OnNewFrame( wxCommandEvent
&WXUNUSED(event
) )
615 wxString filename
= LoadUserImage(image
);
616 if ( !filename
.empty() )
617 (new MyImageFrame(this, filename
, wxBitmap(image
)))->Show();
620 void MyFrame
::OnImageInfo( wxCommandEvent
&WXUNUSED(event
) )
623 if ( !LoadUserImage(image
).empty() )
625 // TODO: show more information about the file
626 wxString info
= wxString
::Format("Image size: %dx%d",
630 int xres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX
),
631 yres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY
);
634 info
+= wxString
::Format("\nResolution: %dx%d", xres
, yres
);
635 switch ( image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT
) )
638 wxFAIL_MSG( "unknown image resolution units" );
641 case wxIMAGE_RESOLUTION_NONE
:
642 info
+= " in default units";
645 case wxIMAGE_RESOLUTION_INCHES
:
649 case wxIMAGE_RESOLUTION_CM
:
655 wxLogMessage("%s", info
);
659 #ifdef wxHAVE_RAW_BITMAP
661 void MyFrame
::OnTestRawBitmap( wxCommandEvent
&WXUNUSED(event
) )
663 (new MyRawBitmapFrame(this))->Show();
666 #endif // wxHAVE_RAW_BITMAP
670 void MyFrame
::OnCopy(wxCommandEvent
& WXUNUSED(event
))
672 wxBitmapDataObject
*dobjBmp
= new wxBitmapDataObject
;
673 dobjBmp
->SetBitmap(m_canvas
->my_horse_png
);
675 wxTheClipboard
->Open();
677 if ( !wxTheClipboard
->SetData(dobjBmp
) )
679 wxLogError(_T("Failed to copy bitmap to clipboard"));
682 wxTheClipboard
->Close();
685 void MyFrame
::OnPaste(wxCommandEvent
& WXUNUSED(event
))
687 wxBitmapDataObject dobjBmp
;
689 wxTheClipboard
->Open();
690 if ( !wxTheClipboard
->GetData(dobjBmp
) )
692 wxLogMessage(_T("No bitmap data in the clipboard"));
696 (new MyImageFrame(this, _T("Clipboard"), dobjBmp
.GetBitmap()))->Show();
698 wxTheClipboard
->Close();
701 #endif // wxUSE_CLIPBOARD
703 void MyFrame
::OnThumbnail( wxCommandEvent
&WXUNUSED(event
) )
706 wxString filename
= wxFileSelector(_T("Select image file"));
707 if ( filename
.empty() )
710 static const int THUMBNAIL_WIDTH
= 320;
711 static const int THUMBNAIL_HEIGHT
= 240;
714 image
.SetOption(wxIMAGE_OPTION_MAX_WIDTH
, THUMBNAIL_WIDTH
);
715 image
.SetOption(wxIMAGE_OPTION_MAX_HEIGHT
, THUMBNAIL_HEIGHT
);
718 if ( !image
.LoadFile(filename
) )
720 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
724 const long loadTime
= sw
.Time();
727 frame
= new MyImageFrame(this, filename
, wxBitmap(image
));
729 wxLogStatus(frame
, "Loaded \"%s\" in %ldms", filename
, loadTime
);
731 wxLogError( _T("Couldn't create file selector dialog") );
733 #endif // wxUSE_FILEDLG
736 //-----------------------------------------------------------------------------
738 //-----------------------------------------------------------------------------
744 if ( !wxApp
::OnInit() )
747 wxInitAllImageHandlers();
749 wxFrame
*frame
= new MyFrame();