Friday, November 8, 2013

Convert Image to String and String to Image


I recently needed to convert a System.Drawing.Image object toSystem.String (Base64 encoded) and vie versa.


So, I've written a helper class named ImageHelper, that have two essentialy two extension methods.




The first method is ImageToString()
public static string ImageToString(this Image image)
{
      if (image == null)
          return String.Empty;
 
      var stream = new MemoryStream();
      image.Save(stream, image.RawFormat);
      var bytes = stream.ToArray();            
 
      return Convert.ToBase64String(bytes);
}
As it's already mentioned, this is an extension method of the System.Drawing.Image class. First, we save the image in memory with its original format, and then we convert the array of bytes that we have in out stream object into a Base64String.

Example  :
var str = Employee.Photo.ImageToString();

The second method is StringToImage()
public static Image StringToImage(this string base64String)
{
      if (String.IsNullOrWhiteSpace(base64String))
          return null;
 
      var bytes = Convert.FromBase64String(base64String);
      var stream = new MemoryStream(bytes);
      return Image.FromStream(stream);
}
This is also a n extenson method, but  of the Systein.String class. First, we convert out base64Stringinto an array of bytes byte[]. and then, after using the stream object, we convert it to an image by using the Image.FromStream().

Example :
// myStr is a Base64String string
var img = myStr.StringToImage();
This article illustrate at the same time the use of extension methods. I recommand using them in such scenarios.

No comments:

Post a Comment

Dharamart.blogspot.in