2013-04-08 35 views
2

當用戶在我的表單上按下「保存團隊」時,我無法將用戶上傳的圖像保存到我的「標識」文件。C#不使用對話框保存圖像

爲了讓您瞭解應用程序的功能,我提供了一個screenshot here,按下添加組後,所有的文本框數據都寫入文本文件,我希望圖像自動保存到預定義的文件夾中。 「,但是當我按下保存時,我得到了GDI ++錯誤。

在閱讀了網絡上的一些舊線程之後,我發現它可能是由文件權限,文件大小,文件名甚至公開流等幾件事引起的。

下面是我目前使用的要保存我的文件,該文件會提示錯誤代碼:由「arsenal.png」

 private void btnAddTeam_Click(object sender, EventArgs e) 
    { 
     //VALIDATION FOR TEXT FILE AND OTHER STUFF HERE... 

     //SAVE THE IMAGE FILE 
     string filePath = picTeamLogo.ImageLocation; 
     Image tempImage = Image.FromFile(filePath); 

     tempImage.Save(@"../logos/"); 
    } 

如果您正在查看的屏幕截圖,請不要混淆我知道那不是完整的文件路徑,它的轉換是在另一個方法中處理的,因爲只需要將文件名寫入文本文件。

如果有人對我的錯在哪裏有任何想法,那麼請將我指向正確的方向,像我剛剛收到的GDI模糊的錯誤是如此頭疼!


Alex。

+1

可以爲用戶提供一個堆棧跟蹤的異常? – DarkSquirrel42 2013-04-08 18:51:02

+0

看起來你需要指定一個文件名而不僅僅是一個目錄。例如@「../logos/test.bmp」。 – Gray 2013-04-08 18:51:18

+0

[在Bitmap.Save方法中發生GDI +中的一般錯誤]的可能重複(http://stackoverflow.com/questions/15862810/a-generic-error-occured-in-gdi-in-bitmap-save-method) – 2013-04-08 18:51:53

回答

1

那是因爲你沒有指定的文件名保存功能!

看看這個:

string filePath = picTeamLogo.ImageLocation; 
FileInfo fi = new FileInfo(filePath); 
Image tempImage = Image.FromFile(fi.FullName); 
tempImage.Save(@"../logo/" + fi.Name); 

現在它工作正常

+1

這正是我所要找的,謝謝梅赫蘭。 – Alex 2013-04-08 20:07:13

+0

不客氣Alex – Mehran 2013-04-09 07:44:42

1

看到這個礦早些時候對類似問題的帖子...

A Generic error occurred in GDI+ in Bitmap.Save method

流將保持鎖定 - 您可以使用內存流作爲一個臨時位置,然後保存。

When either a Bitmap object or an Image object is constructed from a file, the file remains locked for the lifetime of the object. As a result, you cannot change an image and save it back to the same file where it originated. http://support.microsoft.com/?id=814675

string outputFileName = "..."; 
using (MemoryStream memory = new MemoryStream()) 
{ 
    using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite)) 
    { 
     tempImage.Save(memory, ImageFormat.Jpeg); 
     // memory.ToStream(fs) // I think the same 
     byte[] bytes = memory.ToArray(); 
     fs.Write(bytes, 0, bytes.Length); 
    } 
} 

或者替代通過MemoryStream圖像加載到圖像 - 這樣的流不被鎖定在首位...

2

嘗試此方法

public void storeFile(FileUpload File, string dirName) 
    { 
     if (!Directory.Exists(MapPath("~/uploads/" + dirName))) 
     { 
      Directory.CreateDirectory(MapPath("~/uploads/" + dirName)); 
     } 
     string saveLocation = MapPath("~/uploads/" + dirName + "/" +  Path.GetFileName(File.FileName)); 
     File.SaveAs(saveLocation); 


    }