從資料庫儲存和擷取影像是程式設計中的常見任務。雖然看起來很簡單,但如果程式碼未正確實現,則可能會出現問題。在本例中,使用者在將圖像儲存到資料庫並在 Picturebox 控制項中顯示圖像時遇到問題。
為了解決這個問題,讓我們檢查使用者的程式碼並識別潛在問題:
儲存到資料庫:
ImageStream = New System.IO.MemoryStream PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg) ReDim rawdata(CInt(ImageStream.Length - 1))
程式碼無法使用正確的維度初始化原始資料。要正確儲存影像位元組,應重新調整大小以符合影像流的長度:
ReDim rawdata(CInt(ImageStream.Length))
從資料庫擷取:
Dim ad As New System.IO.MemoryStream(100000) Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below)
錯誤出現此問題的原因是廣告記憶體流未正確定位或容量不足。以下程式碼修正了此問題:
ad.Position = 0 Dim im As Image = Image.FromStream(ad)
Dim filename As String = txtName.Text + ".jpg" Dim FileSize As UInt32 conn.Close() 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)" Try conn.Open() With sqlcmd .CommandText = sql .Connection = conn .Parameters.AddWithValue("@FileName", filename) .Parameters.AddWithValue("@FileSize", FileSize) .Parameters.AddWithValue("@File", arrImage) .ExecuteNonQuery() End With Catch ex As Exception MsgBox(ex.Message) Finally conn.Close() End Try
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()
以上是如何有效地從資料庫 Blob 儲存和檢索影像?的詳細內容。更多資訊請關注PHP中文網其他相關文章!