Page 1 of 1

Icon to data URI

Posted: Wed Oct 29, 2014 8:58 pm
by wxBen
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.