WPF - 使用 JpegBitmapDecoder 将文件转换为 Byte[] 到 BitmapSource

标签 wpf image bitmapsource varbinarymax

我需要读取 jpg 文件并将其显示在图像控件中。 以下效果完美:

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

public BitmapSource FetchImage(string URLlink)
{
      JpegBitmapDecoder decoder = null;
      BitmapSource bitmapSource = null;
      decoder = new JpegBitmapDecoder(new Uri(URLlink, UriKind.Absolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
      bitmapSource = decoder.Frames[0];
      bitmapSource.Freeze();
      return bitmapSource;
}

我的问题是我需要将此图像作为 Byte[] (varbinary(MAX) 保存在数据库中并从那里读取它,而不是像上面那样直接从文件中读取。 因此,我需要使用 Byte[] 作为此函数的输入而不是 URLlink 字符串,或者将 BitmapSource 保存为 Byte[]。我该怎么做?

最佳答案

JpegBitmapDecoder 有一个 second constructor接受Stream。只需传入包含您的 byte[]MemoryStream 即可:

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

关于WPF - 使用 JpegBitmapDecoder 将文件转换为 Byte[] 到 BitmapSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7187528/

相关文章:

WPF C# 按钮样式

javascript - Gulp图像优化破坏图像

html - 如何根据窗口大小更改图像大小

c# - 从 BitmapSource 复制到 WriteableBitmap

wpf - 图片异步数据绑定(bind),导致跨线程异常

c# - 如何实例化复杂的控件组并访问它们的值? (wpf 与 Visual Studio )

c# - 是什么导致 WPF 打印机输出被栅格化?

c# - 在 wpf DataGrid 中单击 DataGridTemplateColumn 中的按钮时如何停止行选择

javascript - 如何防止背景图像在更改时闪烁