2013-09-21 50 views
0

我一直有這個問題。 這是我的代碼。'保存圖像時發生GDI +'的一般錯誤

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:\文件夾\ image0.png」和「C:\文件夾\ image1.png」

我第三次按下按鈕,就應該將其保存到「 C:\ Folder \ image0.png「。 相反,它給出了例外'GDI +中發生的一般性錯誤'。

我以前曾經有過類似的問題,並通過添加以下兩行解決了這個問題:

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

它沒有工作這段時間。

+0

嘗試評論'Picbox.Source = ...'-line,看看它是否可以保存它。我的猜測是由於某種原因圖像被該行鎖定。 –

+0

你是對的。我忘了提到這一點 – phil

回答

0

爲了避免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; 
} 
相關問題