简体   繁体   English

如何将字节数组转换为图像文件?

[英]How to convert byte array to image file?

I have browsed and uploaded a png/jpg file in my MVC web app.我已经在我的 MVC Web 应用程序中浏览并上传了一个 png/jpg 文件。 I have stored this file as byte[] in my database.我已将此文件作为 byte[] 存储在我的数据库中。 Now I want to read and convert the byte[] to original file.现在我想读取字节 [] 并将其转换为原始文件。 How can i achieve this?我怎样才能做到这一点?

  1. Create a MemoryStream passing the array in the constructor.创建一个在构造函数中传递数组的MemoryStream
  2. Read the image from the stream using Image.FromStream .使用Image.FromStream从流中读取图像。
  3. Call theImg.Save("theimage.jpg", ImageFormat.Jpeg) .调用theImg.Save("theimage.jpg", ImageFormat.Jpeg)

Remember to reference System.Drawing.Imaging and use a using block for the stream.请记住引用 System.Drawing.Imaging 并为流使用using块。

Create a memory stream from the byte[] array in your database and then use Image.FromStream.从数据库中的 byte[] 数组创建内存流,然后使用 Image.FromStream。

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

May you have trouble with the mentioned solutions on DotNet Core 3.0 or higher您是否在 DotNet Core 3.0 或更高版本上遇到上述解决方案的问题
so my solution is:所以我的解决方案是:

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

Or just use this:或者只是使用这个:

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

File.WriteAllBytes(String, Byte[]) Method (System.IO) | File.WriteAllBytes(String, Byte[]) 方法 (System.IO) | Microsoft Docs 微软文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM