如何在不破坏图片的情况下将图像保存在数据库中?

时间:2014-02-10 05:16:06

标签: mysql vb.net picturebox

我有一个问题,关于使用BLOB数据类型在数据库上保存图像,它成功保存图像,但当我使用我的图片框检索它时,它会破坏我的图像。生病了我的应用程序截图。我正在使用vb.net。

img was ruin.

这是我在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
请伙计们帮帮我。

2 个答案:

答案 0 :(得分:1)

OKAY。使用MEDIUMBLOB或LONGBLOB为该字段。

答案 1 :(得分:0)

你有没有尝试过psren的回答?

将BLOB更改为LONGBLOB

对我有用!