开发者

WPF - Convert file to Byte[] to BitmapSource using JpegBitmapDecoder

I need to read a jpg file and latyer display it in an Image controll. The following works perfectly:

imgTwo.Source = FetchImage(@"C:\Image075.jpg");

public BitmapSource FetchImage(string URLlink)
{
      JpegBitmapDecoder decoder = null;
      BitmapSource bitmapSource = null;
      decoder = new Jpeg开发者_开发技巧BitmapDecoder(new Uri(URLlink, UriKind.Absolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
      bitmapSource = decoder.Frames[0];
      bitmapSource.Freeze();
      return bitmapSource;
}

My problem is that I need to keep this image in a database as Byte[] (varbinary(MAX) and read it from there, not directly from a file as the above does. So I need to either have a Byte[] as input to this function instead of a URLlink string, or save the BitmapSource as Byte[]. How do I do that?


JpegBitmapDecoder has a second constructor that accepts a Stream. Just pass in a MemoryStream containing your byte[]:

using(var stream = new MemoryStream(yourByteArray))
{
    decoder = new JpegBitmapDecoder(stream,
                                    BitmapCreateOptions.PreservePixelFormat,
                                    BitmapCacheOption.OnLoad);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜