0

I have been having quite a problem with this. Here is my code.

    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();
    }

When I start the program, a wpf window pops open. There are two buttons with the events shown in the code.

When I press the up button twice it works fine. This saves two PNGs to the locations

"C:\Folder\image0.png" and "C:\Folder\image1.png"

The third time I press the button, it should save it to "C:\Folder\image0.png" again. Instead, it gives the exception 'A generic error occurred in GDI+'.

I have had a similar problem before, and solved it by adding these two lines:

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

It didn't work this time.

svick
  • 236,525
  • 50
  • 385
  • 514
phil
  • 1,416
  • 2
  • 13
  • 22

1 Answers1

0

To avoid the filelock that BitmapImage creates you have to take care of a bit more initialization. According to this question here on SO, it can be done like this (ported to C# from their VB.Net code).

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;
}
Community
  • 1
  • 1
Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68