首页 >数据库 >mysql教程 >如何在 MySQL 数据库中高效存储和检索图像?

如何在 MySQL 数据库中高效存储和检索图像?

Patricia Arquette
Patricia Arquette原创
2024-11-29 18:15:11232浏览

How to Efficiently Store and Retrieve Images in a MySQL Database?

在数据库中存储和检索图像

简介

本文解决了从数据库存储和检索图像的挑战。提供的初始代码遇到了问题,需要进行更深入的检查并成功解决。

将图像保存到数据库

代码片段演示了如何将图像从 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn