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 wxImage
& image
)
122 Create(parent
, desc
, wxBitmap(image
), image
.GetImageCount(desc
));
125 MyImageFrame(wxFrame
*parent
, const wxString
& desc
, const wxBitmap
& bitmap
)
127 Create(parent
, desc
, bitmap
);
130 bool Create(wxFrame
*parent
,
131 const wxString
& desc
,
132 const wxBitmap
& bitmap
,
135 if ( !wxFrame::Create(parent
, wxID_ANY
,
136 wxString::Format(_T("Image from %s"), desc
),
137 wxDefaultPosition
, wxDefaultSize
,
138 wxDEFAULT_FRAME_STYLE
| wxFULL_REPAINT_ON_RESIZE
) )
143 wxMenu
*menu
= new wxMenu
;
144 menu
->Append(wxID_SAVE
);
145 menu
->AppendSeparator();
146 menu
->AppendCheckItem(ID_PAINT_BG
, _T("&Paint background"),
147 "Uncheck this for transparent images");
148 menu
->AppendSeparator();
149 menu
->Append(ID_RESIZE
, _T("&Fit to window\tCtrl-F"));
150 menu
->AppendSeparator();
151 menu
->Append(ID_ROTATE_LEFT
, _T("Rotate &left\tCtrl-L"));
152 menu
->Append(ID_ROTATE_RIGHT
, _T("Rotate &right\tCtrl-R"));
154 wxMenuBar
*mbar
= new wxMenuBar
;
155 mbar
->Append(menu
, _T("&Image"));
158 mbar
->Check(ID_PAINT_BG
, true);
161 if ( numImages
!= 1 )
162 SetStatusText(wxString::Format("%d images", numImages
), 1);
164 SetClientSize(bitmap
.GetWidth(), bitmap
.GetHeight());
173 void OnEraseBackground(wxEraseEvent
& WXUNUSED(event
))
175 // do nothing here to be able to see how transparent images are shown
178 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
182 if ( GetMenuBar()->IsChecked(ID_PAINT_BG
) )
185 const wxSize size
= GetClientSize();
186 dc
.DrawBitmap(m_bitmap
,
187 (size
.x
- m_bitmap
.GetWidth())/2,
188 (size
.y
- m_bitmap
.GetHeight())/2,
189 true /* use mask */);
192 void OnSave(wxCommandEvent
& WXUNUSED(event
))
195 wxImage image
= m_bitmap
.ConvertToImage();
197 wxString savefilename
= wxFileSelector( wxT("Save Image"),
200 (const wxChar
*)NULL
,
201 wxT("BMP files (*.bmp)|*.bmp|")
202 wxT("PNG files (*.png)|*.png|")
203 wxT("JPEG files (*.jpg)|*.jpg|")
204 wxT("GIF files (*.gif)|*.gif|")
205 wxT("TIFF files (*.tif)|*.tif|")
206 wxT("PCX files (*.pcx)|*.pcx|")
207 wxT("ICO files (*.ico)|*.ico|")
208 wxT("CUR files (*.cur)|*.cur"),
212 if ( savefilename
.empty() )
216 wxFileName::SplitPath(savefilename
, NULL
, NULL
, &extension
);
219 if ( extension
== _T("bmp") )
221 static const int bppvalues
[] =
233 const wxString bppchoices
[] =
239 _T("8 bpp greyscale"),
241 _T("8 bpp own palette"),
245 int bppselection
= wxGetSingleChoiceIndex(_T("Set BMP BPP"),
246 _T("Image sample: save file"),
247 WXSIZEOF(bppchoices
),
250 if ( bppselection
!= -1 )
252 int format
= bppvalues
[bppselection
];
253 image
.SetOption(wxIMAGE_OPTION_BMP_FORMAT
, format
);
255 if ( format
== wxBMP_8BPP_PALETTE
)
257 unsigned char *cmap
= new unsigned char [256];
258 for ( int i
= 0; i
< 256; i
++ )
259 cmap
[i
] = (unsigned char)i
;
260 image
.SetPalette(wxPalette(256, cmap
, cmap
, cmap
));
266 else if ( extension
== _T("png") )
268 static const int pngvalues
[] =
278 const wxString pngchoices
[] =
285 _T("Grey red 16bpp"),
288 int sel
= wxGetSingleChoiceIndex(_T("Set PNG format"),
289 _T("Image sample: save file"),
290 WXSIZEOF(pngchoices
),
295 image
.SetOption(wxIMAGE_OPTION_PNG_FORMAT
, pngvalues
[sel
]);
296 image
.SetOption(wxIMAGE_OPTION_PNG_BITDEPTH
, sel
% 2 ? 16 : 8);
298 // these values are taken from OptiPNG with -o3 switch
299 const wxString compressionChoices
[] =
301 _T("compression = 9, memory = 8, strategy = 0, filter = 0"),
302 _T("compression = 9, memory = 9, strategy = 0, filter = 0"),
303 _T("compression = 9, memory = 8, strategy = 1, filter = 0"),
304 _T("compression = 9, memory = 9, strategy = 1, filter = 0"),
305 _T("compression = 1, memory = 8, strategy = 2, filter = 0"),
306 _T("compression = 1, memory = 9, strategy = 2, filter = 0"),
307 _T("compression = 9, memory = 8, strategy = 0, filter = 5"),
308 _T("compression = 9, memory = 9, strategy = 0, filter = 5"),
309 _T("compression = 9, memory = 8, strategy = 1, filter = 5"),
310 _T("compression = 9, memory = 9, strategy = 1, filter = 5"),
311 _T("compression = 1, memory = 8, strategy = 2, filter = 5"),
312 _T("compression = 1, memory = 9, strategy = 2, filter = 5"),
315 int sel
= wxGetSingleChoiceIndex(_T("Select compression option (Cancel to use default)\n"),
316 _T("PNG Compression Options"),
317 WXSIZEOF(compressionChoices
),
322 const int zc
[] = {9, 9, 9, 9, 1, 1, 9, 9, 9, 9, 1, 1};
323 const int zm
[] = {8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9};
324 const int zs
[] = {0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2};
325 const int f
[] = {0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
326 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8};
328 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_LEVEL
, zc
[sel
]);
329 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL
, zm
[sel
]);
330 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_STRATEGY
, zs
[sel
]);
331 image
.SetOption(wxIMAGE_OPTION_PNG_FILTER
, f
[sel
]);
332 image
.SetOption(wxIMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE
, 1048576); // 1 MB
336 else if ( extension
== _T("cur") )
338 image
.Rescale(32,32);
339 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X
, 0);
340 image
.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y
, 0);
341 // This shows how you can save an image with explicitly
342 // specified image format:
343 saved
= image
.SaveFile(savefilename
, wxBITMAP_TYPE_CUR
);
348 // This one guesses image format from filename extension
349 // (it may fail if the extension is not recognized):
350 image
.SaveFile(savefilename
);
352 #endif // wxUSE_FILEDLG
355 void OnResize(wxCommandEvent
& WXUNUSED(event
))
357 wxImage
img(m_bitmap
.ConvertToImage());
359 const wxSize size
= GetClientSize();
360 img
.Rescale(size
.x
, size
.y
, wxIMAGE_QUALITY_HIGH
);
361 m_bitmap
= wxBitmap(img
);
367 void OnRotate(wxCommandEvent
& event
)
370 if ( event
.GetId() == ID_ROTATE_LEFT
)
373 wxImage
img(m_bitmap
.ConvertToImage());
374 img
= img
.Rotate(angle
, wxPoint(img
.GetWidth() / 2, img
.GetHeight() / 2));
377 wxLogWarning(_T("Rotation failed"));
381 m_bitmap
= wxBitmap(img
);
388 void UpdateStatusBar()
390 wxLogStatus(this, _T("Image size: (%d, %d)"),
392 m_bitmap
.GetHeight());
397 DECLARE_EVENT_TABLE()
400 #ifdef wxHAVE_RAW_BITMAP
402 #include "wx/rawbmp.h"
404 class MyRawBitmapFrame
: public wxFrame
411 REAL_SIZE
= SIZE
- 2*BORDER
414 MyRawBitmapFrame(wxFrame
*parent
)
415 : wxFrame(parent
, wxID_ANY
, _T("Raw bitmaps (how exciting)")),
416 m_bitmap(SIZE
, SIZE
, 24),
417 m_alphaBitmap(SIZE
, SIZE
, 32)
419 SetClientSize(SIZE
, SIZE
*2+25);
426 void InitAlphaBitmap()
428 // First, clear the whole bitmap by making it alpha
430 wxAlphaPixelData
data( m_alphaBitmap
, wxPoint(0,0), wxSize(SIZE
, SIZE
) );
433 wxLogError(_T("Failed to gain raw access to bitmap data"));
436 wxAlphaPixelData::Iterator
p(data
);
437 for ( int y
= 0; y
< SIZE
; ++y
)
439 wxAlphaPixelData::Iterator rowStart
= p
;
440 for ( int x
= 0; x
< SIZE
; ++x
)
443 ++p
; // same as p.OffsetX(1)
450 // Then, draw colourful alpha-blended stripes
451 wxAlphaPixelData
data(m_alphaBitmap
, wxPoint(BORDER
, BORDER
),
452 wxSize(REAL_SIZE
, REAL_SIZE
));
455 wxLogError(_T("Failed to gain raw access to bitmap data"));
459 wxAlphaPixelData::Iterator
p(data
);
461 for ( int y
= 0; y
< REAL_SIZE
; ++y
)
463 wxAlphaPixelData::Iterator rowStart
= p
;
465 int r
= y
< REAL_SIZE
/3 ? 255 : 0,
466 g
= (REAL_SIZE
/3 <= y
) && (y
< 2*(REAL_SIZE
/3)) ? 255 : 0,
467 b
= 2*(REAL_SIZE
/3) <= y
? 255 : 0;
469 for ( int x
= 0; x
< REAL_SIZE
; ++x
)
471 // note that RGB must be premultiplied by alpha
472 unsigned a
= (wxAlphaPixelData::Iterator::ChannelType
)((x
*255.)/REAL_SIZE
);
473 p
.Red() = r
* a
/ 256;
474 p
.Green() = g
* a
/ 256;
475 p
.Blue() = b
* a
/ 256;
478 ++p
; // same as p.OffsetX(1)
488 // draw some colourful stripes without alpha
489 wxNativePixelData
data(m_bitmap
);
492 wxLogError(_T("Failed to gain raw access to bitmap data"));
496 wxNativePixelData::Iterator
p(data
);
497 for ( int y
= 0; y
< SIZE
; ++y
)
499 wxNativePixelData::Iterator rowStart
= p
;
501 int r
= y
< SIZE
/3 ? 255 : 0,
502 g
= (SIZE
/3 <= y
) && (y
< 2*(SIZE
/3)) ? 255 : 0,
503 b
= 2*(SIZE
/3) <= y
? 255 : 0;
505 for ( int x
= 0; x
< SIZE
; ++x
)
510 ++p
; // same as p.OffsetX(1)
518 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
520 wxPaintDC
dc( this );
521 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, BORDER
);
522 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
/2 - BORDER
);
523 dc
.DrawText(_T("This is alpha and raw bitmap test"), 0, SIZE
- 2*BORDER
);
524 dc
.DrawBitmap( m_alphaBitmap
, 0, 0, true /* use mask */ );
526 dc
.DrawText(_T("Raw bitmap access without alpha"), 0, SIZE
+5);
527 dc
.DrawBitmap( m_bitmap
, 0, SIZE
+5+dc
.GetCharHeight());
532 wxBitmap m_alphaBitmap
;
534 DECLARE_EVENT_TABLE()
537 #endif // wxHAVE_RAW_BITMAP
540 // ============================================================================
542 // ============================================================================
544 //-----------------------------------------------------------------------------
546 //-----------------------------------------------------------------------------
548 BEGIN_EVENT_TABLE(MyImageFrame
, wxFrame
)
549 EVT_ERASE_BACKGROUND(MyImageFrame::OnEraseBackground
)
550 EVT_PAINT(MyImageFrame::OnPaint
)
552 EVT_MENU(wxID_SAVE
, MyImageFrame::OnSave
)
553 EVT_MENU_RANGE(ID_ROTATE_LEFT
, ID_ROTATE_RIGHT
, MyImageFrame::OnRotate
)
554 EVT_MENU(ID_RESIZE
, MyImageFrame::OnResize
)
557 //-----------------------------------------------------------------------------
559 //-----------------------------------------------------------------------------
561 #ifdef wxHAVE_RAW_BITMAP
563 BEGIN_EVENT_TABLE(MyRawBitmapFrame
, wxFrame
)
564 EVT_PAINT(MyRawBitmapFrame::OnPaint
)
567 #endif // wxHAVE_RAW_BITMAP
569 //-----------------------------------------------------------------------------
571 //-----------------------------------------------------------------------------
576 ID_ABOUT
= wxID_ABOUT
,
583 IMPLEMENT_DYNAMIC_CLASS( MyFrame
, wxFrame
)
584 BEGIN_EVENT_TABLE(MyFrame
, wxFrame
)
585 EVT_MENU (ID_ABOUT
, MyFrame::OnAbout
)
586 EVT_MENU (ID_QUIT
, MyFrame::OnQuit
)
587 EVT_MENU (ID_NEW
, MyFrame::OnNewFrame
)
588 EVT_MENU (ID_INFO
, MyFrame::OnImageInfo
)
589 EVT_MENU (ID_SHOWTHUMBNAIL
, MyFrame::OnThumbnail
)
590 #ifdef wxHAVE_RAW_BITMAP
591 EVT_MENU (ID_SHOWRAW
, MyFrame::OnTestRawBitmap
)
594 EVT_MENU(wxID_COPY
, MyFrame::OnCopy
)
595 EVT_MENU(wxID_PASTE
, MyFrame::OnPaste
)
596 #endif // wxUSE_CLIPBOARD
600 : wxFrame( (wxFrame
*)NULL
, wxID_ANY
, _T("wxImage sample"),
601 wxPoint(20, 20), wxSize(950, 700) )
603 SetIcon(wxICON(sample
));
605 wxMenuBar
*menu_bar
= new wxMenuBar();
607 wxMenu
*menuImage
= new wxMenu
;
608 menuImage
->Append( ID_NEW
, _T("&Show any image...\tCtrl-O"));
609 menuImage
->Append( ID_INFO
, _T("Show image &information...\tCtrl-I"));
610 #ifdef wxHAVE_RAW_BITMAP
611 menuImage
->AppendSeparator();
612 menuImage
->Append( ID_SHOWRAW
, _T("Test &raw bitmap...\tCtrl-R"));
614 menuImage
->AppendSeparator();
615 menuImage
->Append( ID_SHOWTHUMBNAIL
, _T("Test &thumbnail...\tCtrl-T"),
616 "Test scaling the image during load (try with JPEG)");
617 menuImage
->AppendSeparator();
618 menuImage
->Append( ID_ABOUT
, _T("&About..."));
619 menuImage
->AppendSeparator();
620 menuImage
->Append( ID_QUIT
, _T("E&xit\tCtrl-Q"));
621 menu_bar
->Append(menuImage
, _T("&Image"));
624 wxMenu
*menuClipboard
= new wxMenu
;
625 menuClipboard
->Append(wxID_COPY
, _T("&Copy test image\tCtrl-C"));
626 menuClipboard
->Append(wxID_PASTE
, _T("&Paste image\tCtrl-V"));
627 menu_bar
->Append(menuClipboard
, _T("&Clipboard"));
628 #endif // wxUSE_CLIPBOARD
630 SetMenuBar( menu_bar
);
634 int widths
[] = { -1, 100 };
635 SetStatusWidths( 2, widths
);
636 #endif // wxUSE_STATUSBAR
638 m_canvas
= new MyCanvas( this, wxID_ANY
, wxPoint(0,0), wxSize(10,10) );
640 // 500 width * 2750 height
641 m_canvas
->SetScrollbars( 10, 10, 50, 275 );
644 void MyFrame::OnQuit( wxCommandEvent
&WXUNUSED(event
) )
649 void MyFrame::OnAbout( wxCommandEvent
&WXUNUSED(event
) )
651 (void)wxMessageBox( _T("wxImage demo\n")
652 _T("Robert Roebling (c) 1998,2000"),
653 _T("About wxImage Demo"), wxICON_INFORMATION
| wxOK
);
656 wxString
MyFrame::LoadUserImage(wxImage
& image
)
661 filename
= wxFileSelector(_T("Select image file"));
662 if ( !filename
.empty() )
664 if ( !image
.LoadFile(filename
) )
666 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
668 return wxEmptyString
;
671 #endif // wxUSE_FILEDLG
676 void MyFrame::OnNewFrame( wxCommandEvent
&WXUNUSED(event
) )
679 wxString filename
= LoadUserImage(image
);
680 if ( !filename
.empty() )
681 new MyImageFrame(this, filename
, image
);
684 void MyFrame::OnImageInfo( wxCommandEvent
&WXUNUSED(event
) )
687 if ( !LoadUserImage(image
).empty() )
689 // TODO: show more information about the file
690 wxString info
= wxString::Format("Image size: %dx%d",
694 int xres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX
),
695 yres
= image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY
);
698 info
+= wxString::Format("\nResolution: %dx%d", xres
, yres
);
699 switch ( image
.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT
) )
702 wxFAIL_MSG( "unknown image resolution units" );
705 case wxIMAGE_RESOLUTION_NONE
:
706 info
+= " in default units";
709 case wxIMAGE_RESOLUTION_INCHES
:
713 case wxIMAGE_RESOLUTION_CM
:
719 wxLogMessage("%s", info
);
723 #ifdef wxHAVE_RAW_BITMAP
725 void MyFrame::OnTestRawBitmap( wxCommandEvent
&WXUNUSED(event
) )
727 (new MyRawBitmapFrame(this))->Show();
730 #endif // wxHAVE_RAW_BITMAP
734 void MyFrame::OnCopy(wxCommandEvent
& WXUNUSED(event
))
736 wxBitmapDataObject
*dobjBmp
= new wxBitmapDataObject
;
737 dobjBmp
->SetBitmap(m_canvas
->my_horse_png
);
739 wxTheClipboard
->Open();
741 if ( !wxTheClipboard
->SetData(dobjBmp
) )
743 wxLogError(_T("Failed to copy bitmap to clipboard"));
746 wxTheClipboard
->Close();
749 void MyFrame::OnPaste(wxCommandEvent
& WXUNUSED(event
))
751 wxBitmapDataObject dobjBmp
;
753 wxTheClipboard
->Open();
754 if ( !wxTheClipboard
->GetData(dobjBmp
) )
756 wxLogMessage(_T("No bitmap data in the clipboard"));
760 new MyImageFrame(this, _T("Clipboard"), dobjBmp
.GetBitmap());
762 wxTheClipboard
->Close();
765 #endif // wxUSE_CLIPBOARD
767 void MyFrame::OnThumbnail( wxCommandEvent
&WXUNUSED(event
) )
770 wxString filename
= wxFileSelector(_T("Select image file"));
771 if ( filename
.empty() )
774 static const int THUMBNAIL_WIDTH
= 320;
775 static const int THUMBNAIL_HEIGHT
= 240;
778 image
.SetOption(wxIMAGE_OPTION_MAX_WIDTH
, THUMBNAIL_WIDTH
);
779 image
.SetOption(wxIMAGE_OPTION_MAX_HEIGHT
, THUMBNAIL_HEIGHT
);
782 if ( !image
.LoadFile(filename
) )
784 wxLogError(_T("Couldn't load image from '%s'."), filename
.c_str());
788 const long loadTime
= sw
.Time();
790 MyImageFrame
* const frame
= new MyImageFrame(this, filename
, image
);
791 wxLogStatus(frame
, "Loaded \"%s\" in %ldms", filename
, loadTime
);
793 wxLogError( _T("Couldn't create file selector dialog") );
795 #endif // wxUSE_FILEDLG
798 //-----------------------------------------------------------------------------
800 //-----------------------------------------------------------------------------
806 if ( !wxApp::OnInit() )
809 wxInitAllImageHandlers();
811 wxFrame
*frame
= new MyFrame();