【问题标题】:VB.net - insert/retrieve picture from mysql Database directly to/from a PictureboxVB.net - 从 mysql 数据库直接插入/检索图片到图片框
【发布时间】:2011-02-17 19:32:51
【问题描述】:

我正在寻找一个适用于此的代码 sn-p。通过使用此代码,我已经到了将图片存储为 blob(可能不正确)的地步。

Dim filename As String = txtName.Text + ".jpg"
Dim FileSize As UInt32
Dim ImageStream As System.IO.MemoryStream

ImageStream = New System.IO.MemoryStream
PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg)
ReDim rawdata(CInt(ImageStream.Length - 1))
ImageStream.Position = 0
ImageStream.Read(rawdata, 0, CInt(ImageStream.Length))
FileSize = ImageStream.Length

Dim query As String = ("insert into actors (actor_pic, filename, filesize) VALUES    (?File, ?FileName, ?FileSize)")
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("?FileName", filename)
cmd.Parameters.AddWithValue("?FileSize", FileSize)
cmd.Parameters.AddWithValue("?File", rawData)

cmd.ExecuteNonQuery()

MessageBox.Show("File Inserted into database successfully!", _
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)

但在使用以下代码检索图片框时:

Private Sub GetPicture()
    'This retrieves the pictures from a mysql DB and buffers the rawdata into a memorystream 

    Dim FileSize As UInt32
    Dim rawData() As Byte
    Dim conn As New MySqlConnection(connStr)

    conn.Open()
    conn.ChangeDatabase("psdb")

    Dim cmd As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", conn)
    Cmd.Parameters.AddWithValue("?autoid", Actor1Box.Text)

    Reader = cmd.ExecuteReader
    Reader.Read()

    'data is in memory 

    FileSize = Reader.GetUInt32(Reader.GetOrdinal("filesize"))
    rawData = New Byte(FileSize) {}

    'get the bytes and filesize 
    Reader.GetBytes(Reader.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize)

    Dim ad As New System.IO.MemoryStream(100000)
    ' Dim bm As New Bitmap

    ad.Write(rawData, 0, FileSize)

    Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below)
    Actor1Pic.Image = im

    Reader.Close()
    conn.Close()
    conn.Dispose()
    ad.Dispose()

我在指出的区域收到错误“参数无效”。仅供参考,如果有人甚至有比这更好的(工作)代码示例,我可以插入而不是调试这种混乱,那也很棒。

【问题讨论】:

  • Dim ad As New System.IO.MemoryStream() 出现同样的错误

标签: .net mysql vb.net


【解决方案1】:

好吧,因为没有得到任何帮助,我才解决了这个问题并最终解决了问题。这是我的工作代码。

从 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
    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

从 MySQL 数据库加载返回到 Picturebox

   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()

【讨论】:

    【解决方案2】:

    好吧,当 'Image.FromStream' 期待 System.IO.Stream 时,您正在尝试强制转换类型 MemoryStream

    【讨论】:

      【解决方案3】:

      我刚刚编写了这段代码,作为我对这个论坛的贡献的一部分,虽然不是会员,但我很乐意提供帮助。 当您继续搜索记录而不是搜索一条记录并关闭应用程序以再次搜索时,此代码搜索多条记录及其对应的图像。此代码允许您搜索记录,清除字段输入搜索条件并再次搜索。

          If TextBox3.Text = "" Then ' This is the search field to be used it could be any field from your database that will match the value from the database. Either firstname, phone or email etc
              MsgBox("Nothing to search for from the database", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "Oop!")
          End If
          Try
              conn.Open()
              Dim data As New MySqlDataAdapter("SELECT * FROM users_data WHERE phoneno = '" & TextBox3.Text & "' ", conn)
      
              Dim dTable As New DataTable
              data.Fill(dTable)
      
              If dTable.Rows.Count > 0 Then
                  TextBox1.Text = dTable.Rows(0).Item("firstname")
                  TextBox2.Text = dTable.Rows(0).Item("lastname")
      
                  'Fetching the corresponding image to this member
                  Dim arrImage As Byte()
                  Dim myMS As New IO.MemoryStream
                  If Not IsDBNull(dTable.Rows(0).Item("myimage")) Then
                      arrImage = dTable.Rows(0).Item("myimage")
                      For Each ar As Byte In arrImage
                          myMS.WriteByte(ar)
                      Next
                      PictureBox1.Image = System.Drawing.Image.FromStream(myMS)
                  End If
      
              Else
                  MsgBox("No record found for this Phone No: " & TextBox3.Text & " Enter a valid Phone No or consult the Admin Manager", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Record not found")
                  clear()
              End If
          Catch ex As Exception
              MsgBox(ex.Message)
              Exit Sub
          Finally
              conn.Close()
          End Try
      

      此代码也适用于 MYSQL Server 数据库和 Microsoft SQL 数据库。唯一的区别是将用于 MYSQL Server 的语句 Dim data As New MySqlDataAdapter 更改为 Dim data As New SqlDataAdapter 用于 Microsoft SQL 服务器。晚安所有 StackOverflowers

      【讨论】:

        【解决方案4】:

        VB.NET - 从 MySQL 数据库中直接向图片框插入/检索图片

        示例程序 VISUAL BASIC。净 2017: 我在分享: 1° 表 MySQL 和变量的配置。 2° 视觉设计 3° 代码。

        过程概述:用户将图像放入图片框中。位于图片框中的图像保存在 MySQL 表中。另一个选项是给出图像的 ID (textbox1.text),然后从 MySQL 表中加载图像。还有另一个按钮可以清除图片框,但不是绝对必要的。 这不是一个完美的过程,它只是为了了解图像加载/保存到 MySQL 表的流程,我与你分享我的知识。

        1. 在 MySQL 服务器中配置表。 例子: 使用的表:“imagenes” 变量:

        “idimagen”为 INT。 (主键)

        "imagen" as LONGBLOB (allow null) -------->>>> 图像的容器。

        Mysql表配置示例:

        1. VB.NET 中的设计

        使用的设计形式:

        1. 使用的代码:

        添加参考:MySQL.data 6.10.5.0 您需要导入:MySql.Data.MySqlClient AND Imports System.IO

        Public Class Form1
        
        
        
         Dim Server As String = "XX.XX.XXX.XXX"
            Dim UserID As String = "XXXXXXXXXXXXXX"
            Dim Password As String = "PASSWORD"
            Dim Database As String = "DATABASE NAME"
            Dim Port As Integer = 3306
            Dim AllowUserVariables As Boolean = True
        
            Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        
                Dim ULTIMOID As Integer = 0
                Try
                    Dim xxxxcon As New MySqlConnectionStringBuilder()
                    xxxxcon.Database = Database
                    xxxxcon.Server = Server
                    xxxxcon.UserID = UserID
                    xxxxcon.Password = Password
                    xxxxcon.Port = 3306
                    xxxxcon.AllowUserVariables = True
                    Dim con As New MySqlConnection(xxxxcon.ToString)
                    Dim dbsql As String = "SELECT MAX(idimagen) AS 'ULTIMOID' FROM imagenes;"
                    Dim cmdMy As New MySqlCommand(dbsql, con)
                    con.Open()
                    cmdMy.ExecuteNonQuery()
                    Try
                        ULTIMOID = Convert.ToInt32(cmdMy.ExecuteScalar())
                    Catch ex As Exception
                        ULTIMOID = 0
                    End Try
                    con.Close()
                Catch ex As Exception
                    MsgBox("Problemas leyendo la BASE para obtener el último ID. Error: " & ex.Message)
                End Try
                       Try
                    Dim xxxxcon As New MySqlConnectionStringBuilder()
                    xxxxcon.Database = Database
                    xxxxcon.Server = Server
                    xxxxcon.UserID = UserID
                    xxxxcon.Password = Password
                    xxxxcon.Port = 3306
                    xxxxcon.AllowUserVariables = True
                    Dim FileSize As UInt32
                    Dim con As New MySqlConnection(xxxxcon.ToString)
                    Dim mstream As New System.IO.MemoryStream()
                    PictureBox1.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 imagenes (idimagen, imagen) VALUES(@id, @imagen)"
                    Try
                        con.Open()
                        With sqlcmd
                            .CommandText = sql
                            .Connection = con
                            .Parameters.AddWithValue("@id", ULTIMOID + 1)
                            .Parameters.AddWithValue("@imagen", arrImage)
                            .ExecuteNonQuery()
                        End With
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    Finally
                        con.Close()
                    End Try
        
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            End Sub
        
            Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
                OpenFileDialog2.Filter = "image file (*.jpg, *.bmp, *.png) | *.jpg; *.bmp; *.png| all files (*.*) | *.* "
                If OpenFileDialog2.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
                    PictureBox1.Image = Image.FromFile(OpenFileDialog2.FileName)
                End If
            End Sub
        
            Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
                PictureBox1.Image = Nothing
            End Sub
        
            Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
                Dim xxxxcon As New MySqlConnectionStringBuilder()
                xxxxcon.Database = Database
                xxxxcon.Server = Server
                xxxxcon.UserID = UserID
                xxxxcon.Password = Password
                xxxxcon.Port = 3306
                xxxxcon.AllowUserVariables = True
        
                Dim con As New MySqlConnection(xxxxcon.ToString)
                Try
                    Dim ds As New DataSet
        
                    Dim dbsql As String = "SELECT * FROM imagenes WHERE idimagen = " & TextBox1.Text & ";"
        
                    Dim cmdMy As New MySqlCommand(dbsql, con)
                    con.Open()
                    Dim da As New MySqlDataAdapter(dbsql, con)
                    da.Fill(ds, "Imagenes")
                    con.Close()
                    If ds.Tables("imagenes").Rows.Count > 0 Then
                        Dim bytes As [Byte]() = ds.Tables("imagenes").Rows(0).Item(1)
                        Dim ms As New MemoryStream(bytes)
                        PictureBox1.Image = Image.FromStream(ms)
                    Else
                        MsgBox("No record found for this Phone No: " & TextBox1.Text)
        
                    End If
                Catch ex As Exception
                    MsgBox(ex.Message)
                    Exit Sub
                End Try
            End Sub
        End Class
        

        【讨论】:

          【解决方案5】:

          如果你切换这个会发生什么:

          Dim ad As New System.IO.MemoryStream(100000)
          

          到:

          Dim ad As New System.IO.MemoryStream()
          

          编辑

          VB 数组大小与其他编程语言不同,我认为你需要做一个负1:

          rawData = New Byte(FileSize - 1) {}
          

          编辑 2

          好的,让我们看看你有什么原始二进制数据。所有 JPG 应以FFD8 开头并以FFD9 结尾。设置 rawData 数组后插入以下内容。如果它抛出错误,那么您的 JPEG 信息已损坏。

              If (rawData(0) = &HFF) AndAlso (rawData(1) = &HD8) Then
                  Trace.WriteLine("File start OK")
              Else
                  Throw New ApplicationException("Invalid jpg header")
              End If
          
              If (rawData(rawData.Length - 2) = &HFF) AndAlso (rawData(rawData.Length - 1) = &HD9) Then
                  Trace.WriteLine("File end OK")
              Else
                  Throw New ApplicationException("Invalid jpg footer")
              End If
          

          编辑 3

          我们需要看看数据的前几个字节是什么样子的。运行它并发布输出的内容:

              For I = 0 To 20
                  Trace.Write(Convert.ToString(rawData(I), 16).ToUpperInvariant())
              Next
          

          【讨论】:

          • 甚至没有人有代码 sn-p 以任何方式执行此功能?
          • 感谢您的回复 - 不幸的是它仍然给出同样的错误:(
          • 嗯,是的,它是无效的 jpg 标头。那么它如何存储的问题呢?你能在我的保存图像代码中发现错误吗?
          • 对不起,我是新手 - 以前从未听说过踪迹,因此不得不研究它是如何工作的。原始数据上的跟踪只返回全零。
          • 好的,这意味着数据库中的内容没有进入数组。您是否有一个 GUI 工具可以用来查看表格以确保这些值至少在数据库中?这部分代码看起来是正确的,所以我很确定问题出在尝试拉出图像时。如果您至少可以确认数据在数据库中,那么我建议在此处创建一个新问题(参考这个问题),寻求帮助从 MySql 数据库中获取二进制信息。图片部分不用管,首先我们需要获取二进制信息。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-10
          • 1970-01-01
          相关资源
          最近更新 更多