本文解决了从数据库存储和检索图像的挑战。提供的初始代码遇到了问题,需要进行更深入的检查并成功解决。
代码片段演示了如何将图像从 PictureBox (PbPicture) 保存到MySQL数据库:
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 = "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
从数据库中检索图像并显示将其放入 PictureBox (PbPicture) 中,请按照以下步骤操作:
Dim adapter As New MySqlDataAdapter adapter.SelectCommand = Cmd data = New DataTable adapter = New MySqlDataAdapter("select picture from [yourtable]", conn)
注意: 确保查询仅返回一条记录,因为一次只有一个 PictureBox 可以显示一张图像。
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()
以上是如何在 MySQL 数据库中高效存储和检索图像?的详细内容。更多信息请关注PHP中文网其他相关文章!