Step 1
First, I wrote class, called ImageConverter.cs, and it has two methods.
First method is converting an image to byte array.
- public Image byteArrayToImage(byte[] byteArrayIn)
- {
- MemoryStream ms = new MemoryStream(byteArrayIn);
- Image returnImage = Image.FromStream(ms);
- return returnImage;
- }
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.
- TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[]));
- Response.ContentType = "image/png"
- Response.BinaryWrite((Byte[]) tc.ConvertTo(img, tc));
- public static byte[] ImageToBinary(string imagePath)
- {
- FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
- byte[] b = new byte[fS.Length];
- fS.Read(b, 0, (int) fS.Length);
- fS.Close();
- return b;
- }
- ImageConverter imgCon = new ImageConverter();
- return (byte[]) imgCon.ConvertTo(inImg, typeof(byte[]));
- string path = Server.MapPath("~/Content/Images/user.png");
- byte[] imageByteData = System.IO.File.ReadAllBytes(path);
- string imageBase64Data = Convert.ToBase64String(imageByteData);
- string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);
- Session["UserProfile"] = imageDataURL;