2010-01-12 108 views
3

我需要從OFD打開後保存圖像。 這是我的代碼大氣壓:保存圖像:在GDI +中發生了一般性錯誤。 (vb.net)

Dim ofd As New OpenFileDialog 
ofd.Multiselect = True 
ofd.ShowDialog() 


For Each File In ofd.FileNames 
    Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.png) 
Next 

就行Image.FromFile(File).Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.png)它的錯誤出現。

(注:該應用程序將被建立在這樣這只是我的第一個代碼,這將需要保存不復制)

回答

16

我會檢查兩件事情:

  1. 該目錄你「再保存到 存在
  2. ,你有寫權限 這個目錄
+0

嗯,我我以爲我檢查了目錄存在,但它沒有感謝這麼多,我真的很討厭它,雖然當我花了很多時間試圖找出爲什麼它不工作,然後知道它是一種可笑的簡單:) – 2010-01-12 18:12:45

+0

我很高興你這個星球上唯一發生這種事的人! :) – 2010-01-12 18:16:02

6

打開或保存圖像放鎖定文件。覆蓋這個文件需要你首先在保存鎖的Image對象上調用Dispose()。

我真的不理解你的代碼,但你不得不做這種方式:

For Each File In ofd.FileNames 
     Using img As Image = Image.FromFile(File) 
      img.Save("C:\Users\Jonathan\Desktop\e\tmp.png", Imaging.ImageFormat.Png) 
     End Using 
    Next 

using語句確保IMG對象設置和文件鎖被釋放。

1

圖像放入一個鎖。

例如,我用這個緩衝區圖像保存到內存流中。

byte[] ImageData = new Byte[0]; 
if (BackGroundImage != null) 
    { 
     Bitmap BufferImage = new Bitmap(BackGroundImage); 
     MemoryStream ImageStream = new MemoryStream(); 
     BufferImage.Save(ImageStream, ImageFormat.Jpeg); 
     BufferImage.Dispose(); 
     ImageData = ImageStream.ToArray(); 
     ImageStream.Dispose(); 


     //write the length of the image data...if zero, the deserialier won't load any image 
     DataStream.Write(ImageData.Length); 
     DataStream.Write(ImageData, 0, ImageData.Length); 
    } 
    else 
    { 
     DataStream.Write(ImageData.Length); 
    } 
0

這樣做的一個原因是您已經加載了主圖像的流(MemoryStream或任何其他流)已被丟棄!

這種這種情況下:

這是一個字節數組轉換爲位圖的擴展方法,但使用的語句將配置內存流,這總會引起這樣的錯誤:

public static Bitmap ToBitmap(this byte[] bytes) 
    { 
     if (bytes == null) 
     { 
      return null; 
     } 
     else 
     { 
      using(MemoryStream ms = new MemoryStream(bytes)) 
      { 
       return new Bitmap(ms); 
      } 
     } 
    } 
相關問題