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
- public Image byteArrayToImage(byte[] byteArrayIn) {
- MemoryStream ms = new MemoryStream(byteArrayIn);
- Image returnImage = Image.FromStream(ms);
- return returnImage;
- }
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,
- 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;