【问题标题】:How to save image in database without ruin the picture?如何在不破坏图片的情况下将图像保存在数据库中?
【发布时间】:2017-08-30 06:49:17
【问题描述】:

我在使用 BLOB 数据类型将图像保存到数据库时遇到问题,它成功保存了图像,但是当我使用图片框检索它时,它破坏了我的图像。我会向您展示我的应用程序的屏幕截图。我正在使用 vb.net。

这是我关于以 blob 数据类型保存图像文件的代码。

Dim filename As String = Me.OpenFileDialog1.FileName
    Dim FileSize As UInt32

    Dim conn As New MySqlConnection
    conn = New MySqlConnection("server=localhost;user=root;password=;database=ticketing_system;")
    conn.Open()

    Dim mstream As New System.IO.MemoryStream()
    Me.PbPicture.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
    Me.PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)

    Dim arrImage() As Byte = mstream.GetBuffer()


    FileSize = mstream.Length
    Dim sqlcmd As New MySql.Data.MySqlClient.MySqlCommand
    Dim sql As String
    mstream.Close()

    ' DBconn.Close()

    sql = "INSERT INTO clientreports(img)VALUES(@File)"
    Try
        ' DBconn.Open()
        With sqlcmd
            .CommandText = sql

            .Connection = conn
            .Parameters.AddWithValue("@File", arrImage)
            .ExecuteNonQuery()
        End With

    Catch ex As Exception

        MsgBox(ex.Message)

    Finally

        conn.Close()

    End Try

这是我在图片框中显示图像的代码。

Dim strSQL As String
    Dim conn As New MySqlConnection
    Dim cmd As New MySqlCommand
    Dim dr As MySqlDataReader
    conn = New MySqlConnection("server=localhost;user=root;password=;database=ticketing_system;")


    Dim SQLConnection As MySqlConnection = New MySqlConnection
    'Dim connection As New SqlConnection("connection string here")
    Dim command As New MySqlCommand("SELECT img FROM errdeschis where err_id='31'", conn)

    conn.Open()

    Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
    conn.Close()

    Dim picture As Image = Nothing
    'Create a stream in memory containing the bytes that comprise the image.
    Using stream As New IO.MemoryStream(pictureData)

        'Read the stream and create an Image object from the data.    
        PictureBox1.Image = Image.FromStream(stream)
    End Using

请大家帮帮我。

【问题讨论】:

  • 您是否验证了输入和输出的长度?这可能有助于尝试诊断故障原因。
  • 没有先生。我没有,顺便先生如何验证vs的长度?
  • 您知道如何在将图像存储到数据库之前对其进行转换吗?
  • 我所说的“vs 上的长度”是指将图像放入数据库之前的长度与从数据库中检索后的长度相比的实际长度。看起来你的转换可能很好,但我想知道 BLOB 类型是否有一些长度,你的图片超出了。这就是为什么我对长度感到好奇。

标签: mysql vb.net picturebox


【解决方案1】:

好的。对字段使用 MEDIUMBLOB 或 LONGBLOB。

【讨论】:

    【解决方案2】:

    你试过 psren 的回答吗?

    将 BLOB 更改为 LONGBLOB

    它对我有用!

    【讨论】:

    • 对此我很抱歉,但我只是在澄清他/她的问题的解决方案,因为我也遇到了他/她的问题并找到了 psren s answer and since he/she isnt responding to this. I just wanted to make sure that he/she already checked psren s 的答案。
    • 对不起,如果我犯了错误,我不会再犯了
    • 好的。确保您了解如何使用 Stack Overflow。如果您想宣传已经存在的答案,请对其进行投票 - 这就是制作此功能的原因。
    • 太好了,祝你有美好的一天! :)
    猜你喜欢
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多