在一次开发中把从网络中获取的图片显示到WPF界面上时,使用了下面的代码当运行到
bitmapImage.EndInit(); 时,引发异常:未找到适用于完成此操作的图像处理组件。
private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, bitmap.RawFormat);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, bitmap.RawFormat);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
可这段代码我已经用在其他地方,没有出现此类问题,一开始考虑可能是网络图片的格式有问题,先尝试把它保存成文件,再显示到界面上.结果表明,图片可以正常保存,也可以正常显示,那问题出现在什么地方?
在网上转了半天,没有有效的解决办法.只好自己想办法.
无意中发现我保存文件的时候,因为指定了扩展名,保存代码是这样的:
screen.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
再细看Exception的提示:未找到适用于完成此操作的图像处理组件. 会不会是这里出现问题?赶紧把代码改成了下面这样:
private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
再一试,图片成功显示出来.