本文解決了將影像作為Blob 儲存在資料庫中並檢索它們的問題在Picturebox 控制項中顯示。
要將影像儲存在資料庫中,第一步是將其轉換為二進位格式。這可以使用具有適當 ImageFormat 參數的 Save 方法來實現。
以下是將影像資料插入資料庫的範例:
Dim filename As String = txtName.Text + ".jpg" Dim FileSize As UInt32 Dim mstream As New System.IO.MemoryStream() PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg) Dim arrImage() As Byte = mstream.GetBuffer() FileSize = mstream.Length Dim sqlcmd As New MySqlCommand Dim sql As String mstream.Close() sql = "insert into [your table] (picture, filename, filesize) VALUES(@File, @FileName, @FileSize)" conn.Open() With sqlcmd .CommandText = sql .Connection = conn .Parameters.AddWithValue("@FileName", filename) .Parameters.AddWithValue("@FileSize", FileSize) .Parameters.AddWithValue("@File", arrImage) .ExecuteNonQuery() End With conn.Close()
要從資料庫中擷取影像並將其顯示在圖片框中,請按照下列步驟操作:
Dim adapter As New MySqlDataAdapter adapter.SelectCommand = Cmd data = New DataTable adapter = New MySqlDataAdapter("select picture from [yourtable]", conn) commandbuild = New MySqlCommandBuilder(adapter) adapter.Fill(data) Dim lb() As Byte = data.Rows(0).Item("picture") Dim lstr As New System.IO.MemoryStream(lb) PbPicture.Image = Image.FromStream(lstr) PbPicture.SizeMode = PictureBoxSizeMode.StretchImage lstr.Close()
透過實現這些方法,您可以無縫地在資料庫中儲存和檢索影像,以便在Picturebox控制項中顯示。
以上是如何在資料庫中儲存和擷取影像以供 PictureBox 顯示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!