Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Image, Icon, Cursor, and Anything Else to Base-64 Converter Utility

0.00/5 (No votes)
11 Sep 2008 2  
A simple utility which provides a GUI to converte images to base-64 strings

image-base-64-converter/ConvertToBase64_screenshot.png

Introduction

During a recent project I found myself needing to convert several bitmap images to base-64. I couldn't find a simple tool to achieve this, so I created this very simple utility to facilitate my task. So whilst this article only presents some basic information, its purpose is simply to assist those who could benefit from such a utility.

The latest version of this utility now supports images, icons, cursors, along with any other data file. The new version provides the following functions:

  • string FileToBase64String(string path) - Refer to ImageFromBase64String as a guide to reverse procedure.
  • string ImageToBase64String(Image image, ImageFormat format)
  • string IconToBase64String(Icon image)
  • Image ImageFromBase64String(string base64)
  • Icon IconFromBase64String(string base64)
  • Cursor CursorFromBase64String(string base64)

Background

Images can be stored either externally to your application or internally within some form of resource file. However, sometimes it is useful to store a string representation of an image. For example, when binary transfer is not an option, or if an image is to be stored directly within source code.

Using the Code

Whilst the tool is fairly self contained I thought it would be useful to explain how this utility converts from an image to base-64, and likewise how to convert back again.

Convert from an Image to a base-64 string

public string ImageToBase64String(Image image, ImageFormat format)
{
   MemoryStream memory = new MemoryStream();
   image.Save(memory, format);
   string base64 = Convert.ToBase64String(memory.ToArray());
   memory.Close();

   return base64;
}

Convert from a base-64 string to an Image

public Image ImageFromBase64String(string base64)
{
   MemoryStream memory = new MemoryStream(Convert.FromBase64String(base64));
   Image result = Image.FromStream(memory);
   memory.Close();

   return result;
}

History

 

  • 31st May, 2008: Initial post
  • 11th Sept, 2008: updated version contains specific support for images, icons, and cursors, but it can now also convert any file to base-64

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here