首頁 >資料庫 >mysql教程 >如何在 MySQL 資料庫中高效率地儲存和檢索映像?

如何在 MySQL 資料庫中高效率地儲存和檢索映像?

Patricia Arquette
Patricia Arquette原創
2024-11-29 18:15:11317瀏覽

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