How can I convert byte array into image using asp.net C#? I need to convert model into image for rendering it on MVC view
Thank you
you can do this with the following code:
public Image byteArrayToImage(byte[] source)
{
MemoryStream ms = new MemoryStream(source);
Image ret = Image.FromStream(ms);
return ret;
}
OR in a better way to dispose MemoryStream
public Image byteArrayToImage(byte[] bytesArr)
{
using (MemoryStream memstr = new MemoryStream(bytesArr))
{
Image img = Image.FromStream(memstr);
return img;
}
}
that's it, above code should resolve your issue
thanks
Here is another solution, to convert Byte array into Image using C#
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
//Converts image into Byte array
// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
//Converts Byte Array ino image
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
Note: To get the Image from a jpg or png file you should read the file into a byte array using File.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
Or you can simply try these steps to convert image into byte array
You would have to refer System.Drawing.Imaging and use a using block for the stream.
Here is the code for image to byte and byte to image conversion in C#
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly