zoukankan      html  css  js  c++  java
  • 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, 0, 0);
                    }
                    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",中间的目录名字两边存在空格。在实际创建目录的时候是不被允许两边有空格的,但是自己拼接路径的时候难免在两边多个空格。

  • 相关阅读:
    C# 不用添加WebService引用,调用WebService方法
    贪心 & 动态规划
    trie树 讲解 (转载)
    poj 2151 Check the difficulty of problems (检查问题的难度)
    poj 2513 Colored Sticks 彩色棒
    poj1442 Black Box 栈和优先队列
    啦啦啦
    poj 1265 Area(pick定理)
    poj 2418 Hardwood Species (trie树)
    poj 1836 Alignment 排队
  • 原文地址:https://www.cnblogs.com/kissfu/p/3422829.html
Copyright © 2011-2022 走看看