Load a byte[] into an Image at Runtime

后端 未结 4 1321
醉话见心
醉话见心 2021-01-11 13:09

I have a byte[] that is represented by an Image. I am downloading this Image via a WebClient. When the WebClient

相关标签:
4条回答
  • 2021-01-11 13:22

    You can use a BitmapImage, and sets its StreamSource to a stream containing the binary data. If you want to make a stream from a byte[], use a MemoryStream:

    MemoryStream stream = new MemoryStream(bytes);
    
    0 讨论(0)
  • 2021-01-11 13:24

    One way that I figured out how to do it so that it was both fast and thread safe was the following:

     var imgBytes = value as byte[];
     if (imgBytes == null)
      return null;
     using (var stream = new MemoryStream(imgBytes))
       return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    

    I threw that into a converter for my WPF application after running the images as Varbinary from the DB.

    0 讨论(0)
  • 2021-01-11 13:28

    Create a BitmapImage from the MemoryStream as below:

    MemoryStream byteStream = new MemoryStream(bytes);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = byteStream;
    image.EndInit();
    

    And in XAML you can create an Image control and set the above image as the Source property.

    0 讨论(0)
  • 2021-01-11 13:44

    In .Net framework 4.0

    using System.Drawing;
    using System.Web;
    
    private Image GetImageFile(HttpPostedFileBase postedFile)
    {
       if (postedFile == null) return null;
       return Image.FromStream(postedFile.InputStream);
    }
    
    0 讨论(0)
提交回复
热议问题