Search code examples
c++wxwidgets

Add Image in wxWidgets


i just started to learn wxWidgets and I'm trying to create some kind of Image Opener. But i cant understand how to add an image... i seen some stuff about wxImage, wxBitMap,wxStaticBitmap, but i couldn't understand any of them or the difference between them.

#include <wx/wx.h>
#include <wx/filedlg.h>
#include <wx/wfstream.h>

class MyApp : public wxApp
{
public:
   virtual bool OnInit();
};

class MyFrame : public wxFrame
{
public:
   MyFrame (const wxString& event);

   void OnOpen(wxCommandEvent& event);
   void OnQuit(wxCommandEvent& event);

private:
   DECLARE_EVENT_TABLE();
};

DECLARE_APP(MyApp);
IMPLEMENT_APP(MyApp);

bool MyApp::OnInit()
{
   MyFrame *frame = new MyFrame(wxT("Minimal wxWidgets App"));
   frame->Show(true);
   return true;
}

BEGIN_EVENT_TABLE(MyFrame, wxFrame)
   EVT_MENU(wxID_OPEN, MyFrame::OnOpen)
   EVT_MENU(wxID_EXIT, MyFrame::OnQuit)
END_EVENT_TABLE()

void MyFrame::OnOpen(wxCommandEvent& event)
{
   wxFileDialog openFileDialog(this, ("Open JPEG file"), "", "", "JPEG files (*.jpg)|*jpg", wxFD_OPEN|wxFD_FILE_MUST_EXIST);

   if(openFileDialog.ShowModal() == wxID_CANCEL)
      return;

   wxFileInputStream input_stream(openFileDialog.GetPath());

   if(!input_stream.IsOk())
   {
      wxLogError("Cannot Open File '%s'.", openFileDialog.GetPath());
      return;
   }
}

void MyFrame::OnQuit(wxCommandEvent& event)
{
   Close(true);
}

MyFrame::MyFrame(const wxString& title) : wxFrame(NULL, wxID_ANY, title)
{    
   wxMenuBar * menuBar = new wxMenuBar;
   wxMenu * exitMenu = new wxMenu;
   wxMenu * openMenu = new wxMenu;

   exitMenu->Append(wxID_EXIT);
   openMenu->Append(wxID_OPEN);

   menuBar->Append(openMenu, "&Open");
   menuBar->Append(exitMenu, "&Exit");

   SetMenuBar(menuBar);

   CreateStatusBar(2);
   SetStatusText(wxT("Image Opener !"));
}

can someone show an example of adding an image on wxwidgets ? or adding it to my code . thanks for help !


Solution

  • wxImage is a portable representation of an image, wxBitmap is a platform-specific but more efficient equivalent. Generally speaking, wxImage is convenient for working with image data, but it needs to be converted to wxBitmap to be displayed.

    Both of these classes are just abstract images, while wxStaticBitmap is a control showing an image, i.e. something you can really see on screen.

    The image sample (under samples directory of your wxWidgets distribution) shows how to use the different classes and draw images directly.