vb.net 存取資料庫中的圖片 (轉)

gugu99發表於2008-08-14
vb.net 存取資料庫中的圖片 (轉)[@more@]

   以MS自帶的Northwnd為例,其中有個表是Categories,有四個四段,其中有一個是Image型別的Picture欄位.我們首先新增一張bmp圖片到最後一行的Picture中,然後在讀出來顯示到Image中.

  新增一個DataAdapter1,用嚮導設定聯接資料庫為Northwnd,SQL語句為 [Category ID], [Category Name], Description, Picture FROM Categories.生成一個資料集為dataset1. 然後新增兩個按鈕分別表示寫圖片到資料庫和讀資料庫,還有一個Image控制元件用於顯示圖片.

新增以下程式碼

 Private Sub Form1_Load(ByVal sender As System., ByVal e As System.EventArgs) Handles MyBase.Load
  SqlDataAdapter1.Fill(DataSet11)
  End Sub

'從資料庫讀取圖片暫時為monkey.bmp,然後載入到image控制元件裡面. 
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadPicFrom.Click
  Try
  Dim data As Byte() = DataSet11.Tables(0).Rows(7).Item(3)
  Dim myfilestream As New System.IO.FileStream(Application.StartupPath & "monkey.bmp", IO.FileMode.Create)
  myfilestream.Write(data, 0, data.Length)
  myfilestream.Close()
  PictureBox1.Image = New Bitmap(Application.StartupPath & "monkey.bmp")
  Catch
  End Try
  End Sub


  '把C:6.bmp寫入庫中,你可以改為自己的圖片.
  Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsertPicToDb.Click
  Dim myfilestream As New System.IO.FileStream("c:6.bmp", IO.FileMode.Open)
  Dim data() As Byte
  ReDim data(myfilestream.Length - 1)
  myfilestream.Read(data, 0, myfilestream.Length)
  myfilestream.Close()
  DataSet11.Tables(0).Rows(7).Item(3) = data
  SqlDataAdapter1.Update(DataSet11.GetChanges())
  End Sub

 

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-1008982/,如需轉載,請註明出處,否則將追究法律責任。

相關文章