WPF BitmapImage - EndInit() throwing NotSupportedException
本文关键字:throwing NotSupportedException EndInit BitmapImage WPF | 更新日期: 2023-09-27 18:26:54
我必须将BitmapImage(内部为JPEG)转换为byte[],然后返回。
这是我的代码:
using System.IO;
using System.Windows.Media.Imaging;
public class CImageConverter
{
//
public BitmapImage ByteArray_To_BitmapImage(byte[] _binaryData)
{
BitmapImage _bitmapImage = new BitmapImage();
//
_bitmapImage.BeginInit();
_bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
_bitmapImage.StreamSource = new MemoryStream(_binaryData);
_bitmapImage.EndInit();
//
return _bitmapImage;
}
//
public byte[] BitmapImage_To_ByteArray(BitmapImage _bitmapImage)
{
byte[] bytes;
//
using(MemoryStream ms = new MemoryStream())
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(_bitmapImage));
encoder.Save(ms);
bytes = ms.ToArray();
}
//
return bytes;
}
}
看来BitmapImage_To_ByteArray工作正常。
但是ByteArray_To_BitmapImage在EndInit()方法中抛出NotSupportedException。
该消息是(使用网络翻译器翻译):
找不到适合的图像处理组件完成此操作。
我在网上发现了类似的问题,但答案都不起作用。通常的答案是"我试过你的代码了——我一切都很好。"
我也发现了这个建议,但不明白,如何使用它
谢谢你的帮助!
public BitmapImage ToImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
return image;
}
}
你试过这个吗?