【问题标题】:'A generic error occurred in GDI+' when saving an image保存图像时“GDI+ 中发生一般错误”
【发布时间】:2013-09-26 22:58:55
【问题描述】:

我对此一直有很大的问题。 这是我的代码。

    int frame = 0;

    //This is a wpf button event
    private void up_Click(object sender, RoutedEventArgs e)
    {
        frame++;
        LoadPic();
    }
    private void LoadPic()
    {
        string fn = @"C:\Folder\image" + (frame % 2).ToString() + ".png";
        Bitmap bmp = new Bitmap(302, 170);
        bmp.Save(fn);
        bmp.Dispose();

        //Picebox is a wpf Image control
        Picbox.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(fn));
    }

    private void down_Click(object sender, RoutedEventArgs e)
    {
        frame--;
        LoadPic();
    }

当我启动程序时,会弹出一个 wpf 窗口。代码中显示的事件有两个按钮。

当我按两次向上按钮时,它工作正常。这会将两个 PNG 保存到位置

“C:\Folder\image0.png”和“C:\Folder\image1.png”

我第三次按下按钮时,它应该再次将其保存到“C:\Folder\image0.png”。 相反,它会给出异常“GDI+ 中发生一般错误”。

我之前也遇到过类似的问题,加了这两行就解决了:

GC.Collect();
GC.WaitForPendingFinalizers();

这次不行。

【问题讨论】:

  • 尝试注释掉Picbox.Source = ...-line,然后看看它是否可以保存它。我的猜测是该图像由于某种原因被该行锁定。
  • 你是对的。我忘了提这个

标签: c# gdi


【解决方案1】:

为了避免BitmapImage 创建的文件锁,您必须多做一些初始化工作。根据this question here on SO,可以这样做(从他们的VB.Net代码移植到C#)。

private void LoadPic()
{
    string fn = @"C:\Folder\image" + (frame % 2).ToString() + ".png";
    Bitmap bmp = new Bitmap(302, 170);
    bmp.Save(fn);
    bmp.Dispose();

    var img = new System.Windows.Media.Imaging.BitmapImage();
    img.BeginInit();
    img.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
    img.UriSource = new Uri(fn);
    img.EndInit();
    Picbox.Source = img;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-02
    • 2019-01-02
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多