如何将图像插入数据库

时间:2013-12-29 14:58:09

标签: vb.net visual-studio-2012

单击保存按钮时,它将存储在数据库中,并在单击显示按钮

后检索该图像
Private Sub btnSve_Click(sender As Object, e As EventArgs) Handles btnSve.Click
    Dim data As IDataObject
    Dim bmap As Image
    data = Clipboard.GetDataObject()
    If Data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
        bmap = CType(Data.GetData(GetType(System.Drawing.Bitmap)), Image)
        picCapture.Image = bmap

        ''Stop Device Capture 
        ClosePreviewWindow()

        'Set Button 
        btnSave.Enabled = False
        btnStop.Enabled = False
        btnStart.Enabled = True

        'Set Save Dialog 
        sfdImage.FileName = ""
        sfdImage.Title = "Save Picture"
        sfdImage.Filter = "Bitmap|*.bmp|Jpeg|*.jpg|GIF|*.gif|PNG|*.png"

        ' If File Name Not Equal "" then Save The File 
        If sfdImage.ShowDialog = DialogResult.OK Then
            Select Case Microsoft.VisualBasic.Right$(sfdImage.FileName, 3)
                Case Is = "bmp"
                    bmap.Save(sfdImage.FileName, Imaging.ImageFormat.Bmp)
                Case Is = "jpg"
                    bmap.Save(sfdImage.FileName, Imaging.ImageFormat.Jpeg)
                Case Is = "gif"
                    bmap.Save(sfdImage.FileName, Imaging.ImageFormat.Gif)
                Case Is = "png"
                    bmap.Save(sfdImage.FileName, Imaging.ImageFormat.Png)
            End Select
        End If

    End If

    data = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

假设您熟悉System.Data.SqlClient命名空间,可以使用以下方法保存图像:

Dim data As Byte()

Using stream As New MemoryStream()
    bmap.Save(stream, ImageFormat.Jpeg)
    data = stream.GetBuffer()
End Using

Dim parameter As New SqlParameter("@DB_COLUMN_NAME", SqlDbType.Image, data.Length)

parameter.Value = data
mysqlcommand.Parameters.Add(parameter)