Icon to data URI

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
wxBen
Knows some wx things
Knows some wx things
Posts: 42
Joined: Wed Jun 06, 2012 4:44 pm
Location: Calgary, Canada

Icon to data URI

Postby wxBen » Wed Oct 29, 2014 8:58 pm

Suppose you are on Windows and you have an HICON and you need to generate HTML with the image embedded inside the HTML, that is, you need to convert it to something of the form:

Code: Select all

<img src="data:image/png;base64, iVBORw bla bla"/>

How can you do it, especially if the icon could be anything, you need to do it on the fly? How can you do it in wxWidgets?

The following works super for me:

Code: Select all

wxString IconToDataURI(HICON hicon)
   {
   wxString ret;

   //Create a wxIcon object:
   wxSize size = wxGetHiconSize(hicon);
   wxIcon tmpIcon;
   tmpIcon.SetSize(size.x, size.y);
   tmpIcon.SetHICON((WXHICON)hicon);

   //And from that make a wxBitmap object:
   wxBitmap bitmap;
   bitmap.CopyFromIcon(tmpIcon);
   wxImage img(bitmap.ConvertToImage());

   //Which can save to a PNG file on disk:
   wxBitmapType type = wxBITMAP_TYPE_PNG;

   wxString prefix = wxT("pspng");
   wxFileName fname;
   fname.AssignTempFileName(prefix);
   wxString fnames = fname.GetFullPath();
   bool ok = img.SaveFile(fnames, type);
   if (ok)
      {
      ret = wxT("src=\"data:image/png;base64,");

      wxFile wf(fnames);
      wxFileOffset ssize = wf.Length();
      char* sbuffer = new char[ssize];
      wf.Read(sbuffer, ssize);
      wf.Close();
      wxRemoveFile(fnames);

      wxString enc = wxBase64Encode(sbuffer, ssize);

      delete[] sbuffer; sbuffer = 0;

      ret += enc;

      ret += wxT("\"");
      }
   return ret;
   }

I modified the method slightly to remove some snippets not relevant here, but the idea is solid. If anyone wants to add this as a nice utility method to wxWidgets in general, please do ahead. Also, some error checking is missing.

Return to “The Code Dump”

Who is online

Users browsing this forum: No registered users and 1 guest