Exception:A generic error occurred in GDI+

分析:

一般出现这种问题都是GDI和原数据(比如Bitmap)是同一个实体,只不过是两个引用。换句话说就是这个路径的图片被GDI占用啦。

还有一种情况是路径有问题。

场景一:

WPF的Image控件的Source属性绑定一个图片路径的时候需要吧Bitmap转换成ImageSource。

Bitmap _lastBitmap;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ if (value != null && System.IO.File.Exists(value.ToString()))
{
if (_lastBitmap != null)
_lastBitmap.Dispose(); var path = value.ToString();
Bitmap bmp = (Bitmap)Bitmap.FromFile(path);
_lastBitmap = new Bitmap(bmp.Width, bmp.Height);
using (Graphics g = Graphics.FromImage(_lastBitmap))
{
g.DrawImageUnscaled(bmp, , );
}
bmp.Dispose();
return PublicMethod.BitMapToImageSource(_lastBitmap);
}
return null;
}
public static ImageSource BitMapToImageSource(Bitmap bmp)
{
BitmapSource returnSource;
try
{
returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
catch
{
returnSource = null;
}
return returnSource;
}

在Convert的方法里面用到啦Graphics,就是为啦吧图片这个原数据分成两个实体,一个为GDI显示,一个为以后别的操作而用,比如:

保存相同路径的不同图片,需要通知界面更新重新绑定Path对应的图片。Bitmap.Save(“Path”).

场景二:

比如保存的路径为"D:\ my_testfiles \hello.png",中间的目录名字两边存在空格。在实际创建目录的时候是不被允许两边有空格的,但是自己拼接路径的时候难免在两边多个空格。

上一篇:BZOJ1878 [SDOI2009] HH的项链 [莫队,卡常]


下一篇:Go linux 实践3