how to convert byte array into image?

How can I convert byte array into image using C#? I need to convert model into image for rendering it on MVC view

Thank you

Asked by:- Vipin
: 235 At:- 6/19/2017 10:36:11 AM C# byte-array image

2 Answers
profileImage Answered by:- jaya

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;

that's it, above code should resolve your issue


At:- 6/19/2017 1:10:53 PM
thanks, the above answer worked for me 0
By : Vipin - at :- 8/13/2017 8:17:09 AM

profileImage Answered by:- vikas_jk

Here is another solution, to convert Byte array into Image using C#

Convert Byte Array to Image File in 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

  1. Create a MemoryStream passing the array in the constructor.
  2. Read the image from the stream using Image.FromStream.
  3. Call theImg.Save("theimage.jpg", ImageFormat.Jpeg), to save it as image.
  4. Return saved file path.

You would have to refer System.Drawing.Imaging and use a using block for the stream.

At:- 7/28/2017 7:06:04 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use