Converting base64 String Back to an Image

In a project I’m working on, images are sent over from a web service or are sitting on the users disk… both in an xml format. It’s easy enough to save anything as base64 encoded, but how do you get it back to an actual image object? It’s a little tricky.

Lets say you have your base64 string in a variable already. Well while it was stored in the xml file it could have gotten some extra characters in it… namely empty spaces and “\r\n”. We need to remove them first. Here is the function that will do it:

public string FixBase64ForImage(string Image)
{
   System.Text.StringBuilder sbText =
      new System.Text.StringBuilder(Image,Image.Length);
   sbText.Replace("\r\n", String.Empty);
   sbText.Replace(" ", String.Empty);
   return sbText.ToString();
}

Now that the string it cleaned up the steps are:

  1. Convert the base64 string into a byte array.
  2. Convert the byte array into an in memory stream.
  3. Then finally convert the byte array into an image. This is actually a two step process (on one line of code).

if (ImageText.Length > 0)
{
   Byte[] bitmapData = new Byte[ImageText.Length];
   bitmapData = Convert.FromBase64String(FixBase64ForImage
     (ImageText));
   System.IO.MemoryStream streamBitmap = new 
     System.IO.MemoryStream(bitmapData);
   Bitmap bitImage = new 
     Bitmap((Bitmap)Image.FromStream(streamBitmap));
}

That’s all there is to it!

 

Tip Submitted By: David McCarter

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s