[WINFORM]PictureBox顯示圖片的方式

來源:互聯網
上載者:User

最近看程式時,發現使用PictureBox顯示圖片時,會有「System.Drawing.Image.FromFile  <System.OutOfMemoryException> 記憶體不足。」的錯誤。Google一下,發現有人說別使用Image.FromFile,所以在此Log一下。

Assign給PictureBox.Image屬性方式有以下方式

方法1, 使用Image.FromFile

Me.PictureBox1.Image = Image.FromFile("f:\img1.jpg")

 

 

方法2, 使用Image.FromStream

 Dim fs As System.IO.FileStream = System.IO.File.OpenRead("f:\img1.jpg")

Me.PictureBox1.Image = Image.FromStream(fs)


 fs.Close()

 

 

建議使用方法2,因為使用方法1,Assign完後,image檔還是會被Lock,而方法2則不會。

清PictureBox.Image屬性的方式有以下方式,

方法1,直接用PictureBox.Image

If Not (Me.PictureBox1.Image Is Nothing) Then

PictureBox1.Image.Dispose()


    PictureBox1.Image = Nothing

End If


 

 

方法2,透過System.Drawing.Bitmap

Dim oldImg As System.Drawing.Bitmap = PictureBox1.Image

PictureBox1.Image = Nothing


If IsNothing(oldImg) = False Then

oldImg.Dispose()


End If

 

 

在Assign Image到PictureBox.Image之前,要先把原Image Dispose掉哦! 不然memory會一直吃下去哦!

參考

PictureBox Dispose Problem

GDI+ 中發生一般性錯誤 System.OutOfMemoryException: 記憶體不足

範例

Download Example

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.