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)
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();
string base64 = Convert.ToBase64String(memory.ToArray());
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);
- 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