C# 之 後台載入圖片Image

來源:互聯網
上載者:User

標籤:

  命名空間為 System.Drawing ,Image.FromFile  一旦使用後,對應的檔案在一直調用其產生的Image對象被Disponse前都不會被解除鎖定,這就造成了一個問題,就是在這個圖形被解鎖前無法對映像進行操作(比如刪除,修改等操作).

  解決方案常用如下:

[1]在要進行檔案操作前將Image對象銷毀.

PictureBox picbox;if(picbox.Image!=null)picbox.Image.Disponse();

 

[2]在載入映像的時候用一種方法替代:

Image img = Image.FromFile(filepath);Image bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);Graphics g = Graphics.FromImage(bmp);g.DrawImage(img, 0, 0);g.Flush();g.Dispose();img.Dispose();//下面開始使用bmp作為顯示的Image對象Image img = Image.FromFile(filepath);Image bmp = new Bitmap(img);img.Dispose();

 

[3]在載入映像的時候用一種方法替代:

System.IO.FileStream fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",System.IO.FileMode.Open, System.IO.FileAccess.Read)PictureBox1.Image = System.Drawing.Image.FromStream(fs)fs.Close()

  Image類的FromFile方法開啟檔案後沒有關閉,導致檔案鎖定,無法進行刪除、移動等操作。

  改而使用FromStream方法,代碼如下:

//讀取檔案流FileStream fileStream = new FileStream(iconPath, FileMode.Open, FileAccess.Read);int byteLength = (int)fileStream.Length;byte[] fileBytes = new byte[byteLength];fileStream.Read(fileBytes, 0, byteLength);//檔案流關閉,檔案解除鎖定fileStream.Close();Pictrue.Image = Image.FromStream(new MemoryStream(fileBytes));

  因為FromStream方法參數應用的流必須一直保持開啟,故代碼中有一個檔案流向MemeoryStream流的轉換,從而可以關閉檔案流,保持MemoryStream流的開啟狀態。

C# 之 後台載入圖片Image

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.