从数据库存储和检索图像是编程中的常见任务。虽然看起来很简单,但如果代码未正确实现,则可能会出现问题。在本例中,用户在将图像保存到数据库并在 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中文网其他相关文章!