How to save and Retrive PictureBox Image to Sql Se

2020-03-31 06:22发布

问题:

In my windows application I have to display image in Windows Form PictureBox which will be browsed by OpenFile Dialog, and then save PictureBox image to Sql Server 2008 R2 Varbinary(Max) Column and Show Picture saved in Sql Server 2008 R2 Varbinary(Max) column to PictureBox Using VB.NET 2010.

I have used the following code to load Picture from physical drive to PictureBox

    Private Sub btnPicBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPicBrowse.Click
    With Me.OpenFileDialog1
        .FileName = ""
        .Filter = "Image Files(*.BMP;*.JPG;*.JEPG;*.GIF)|*.BMP;*.JPG;*.JEPG;*.GIF|All files (*.*)|*.*"
        .RestoreDirectory = True
        .ValidateNames = True
        .CheckFileExists = True
        If .ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.PictureBox1.Image.Dispose()
            Me.PictureBox1.Image = System.Drawing.Image.FromFile(.FileName)
            Me.lblPicPath.Text = .FileName
        End If
    End With
End Sub

Now I have to save this Image to SQL SERVER 2008 Database VarBinary (MAX) Column and Then Show Picture saved in Sql Server 2008 R2 Varbinary(Max) column to PictureBox Using VB.NET 2010.

Thanks & Regards

JYOTIRMOY

回答1:

Found some cool method on youtube a while back you create a function that receives the picture and converts it to bytes and saves it to bytes in the SQLServer DB, and when you retrieve it it will show up on the picture box. Here is the code implement it and tell me if it works...if it does vote for my answer please:

 Public Function ConvertImage(ByVal myImage As Image) As Byte()

    Dim mstream As New MemoryStream
    myImage.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)

    Dim myBytes(mstream.Length - 1) As Byte
    mstream.Position = 0

    mstream.Read(myBytes, 0, mstream.Length)

    Return myBytes

End Function


So if you are saving using a stored procedure just pass the image in the picturebox as the argument e.g pictureBoxUser.Image