Image Conversion And Storing Image Value In Session

Recently I was looking for a class which could convert a System.Drawing.Image to byte[] array and vice versa. After a lot of searching on Google, I realized that it would be faster for me to write this class and also share it with the community.

The class which I wrote is called ImageConverter.cs. The class has two methods.

First method: Convert Image to byte - array

  1. public Image byteArrayToImage(byte[] byteArrayIn) {  
  2.     MemoryStream ms = new MemoryStream(byteArrayIn);  
  3.     Image returnImage = Image.FromStream(ms);  
  4.     return returnImage;  
  5. }  
This method uses the Image.FromStream method in the Image class to create a method from a memory stream which has been created using a byte array. The image thus created is returned in this method.

First, convert the image into a byte array using ImageConverter class. Then specify the mime typeof your png image, and voila!

Here's an example,
  1. TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[]));  
  2. Response.ContentType = "image/png"  
  3. Response.BinaryWrite((Byte[]) tc.ConvertTo(img, tc));  
  4. public static byte[] ImageToBinary(string imagePath) {  
  5.     FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read);  
  6.     byte[] b = new byte[fS.Length];  
  7.     fS.Read(b, 0, (int) fS.Length);  
  8.     fS.Close();  
  9.     return b;  
  10. }  
  11. ImageConverter imgCon = new ImageConverter();  
  12. return (byte[]) imgCon.ConvertTo(inImg, typeof(byte[]));  
  13. string path = Server.MapPath("~/Content/Images/user.png");  
  14. byte[] imageByteData = System.IO.File.ReadAllBytes(path);  
  15. string imageBase64Data = Convert.ToBase64String(imageByteData);  
  16. string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);  
  17. Session["UserProfile"] = imageDataURL;