34

I have browsed and uploaded a png/jpg file in my MVC web app. I have stored this file as byte[] in my database. Now I want to read and convert the byte[] to original file. How can i achieve this?

4 Answers 4

39
  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).

Remember to reference System.Drawing.Imaging and use a using block for the stream.

Sign up to request clarification or add additional context in comments.

1 Comment

The Image roundtrip makes no sense if the byte array already contains a valid image. Just ues File.WriteAllBytes() or whatever to directly write the byte array's contents to a file.
28

Create a memory stream from the byte[] array in your database and then use Image.FromStream.

byte[] image = GetImageFromDatabase();
MemoryStream ms = new MemoryStream(image);
Image i = Image.FromStream(ms);

Comments

9

May you have trouble with the mentioned solutions on DotNet Core 3.0 or higher
so my solution is:

using(var ms = new MemoryStream(yourByteArray)) {
   using(var fs = new FileStream("savePath", FileMode.Create)) {
      ms.WriteTo(fs);
   }
}

Comments

5

Or just use this:

System.IO.File.WriteAllBytes(string path, byte[] bytes)

File.WriteAllBytes(String, Byte[]) Method (System.IO) | Microsoft Docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.