Image Conversion And Storing The Image Value Using C#

Step 1

First, I wrote class, called ImageConverter.cs, and it has two methods.

First method is converting an image to byte array. 
  1. public Image byteArrayToImage(byte[] byteArrayIn)   
  2. {    
  3.     MemoryStream ms = new MemoryStream(byteArrayIn);    
  4.     Image returnImage = Image.FromStream(ms);    
  5.     return returnImage;    
  6. }   
This method used Image.FromStream to create a method from the memory stream, which creates byte array.
 
Step 2

Now, convert the image into a byte array, using an image convertor class and specify mime type of your png. 
  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.  {    
  6.     FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read);    
  7.     byte[] b = new byte[fS.Length];    
  8.     fS.Read(b, 0, (int) fS.Length);    
  9.     fS.Close();    
  10.     return b;    
  11. }    
  12. ImageConverter imgCon = new ImageConverter();    
  13. return (byte[]) imgCon.ConvertTo(inImg, typeof(byte[]));    
  14. string path = Server.MapPath("~/Content/Images/user.png");    
  15. byte[] imageByteData = System.IO.File.ReadAllBytes(path);    
  16. string imageBase64Data = Convert.ToBase64String(imageByteData);    
  17. string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);    
  18. Session["UserProfile"] = imageDataURL;