本文解决了将图像作为 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中文网其他相关文章!