我需要读取 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/