1

请我使用 vb.net 2008 和 Sql 2008,我必须将图片保存到数据库中。当我最初运行代码时,它正在保存,后来我意识到它给了我 NullReferenceException 被捕获。你调用的对象是空的。我只是困惑!

下面的代码

Imports System.Data.SqlClient
Imports System.IO


Private Sub btnImage1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage1.Click
        'Code to load picture
        Dim OpenFileDialog1 As New OpenFileDialog
        OpenFileDialog1.Filter = "JPG|*.jpg|BITMAP|*.bmp|GIF|*.gif"
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName <> "" AndAlso IO.File.Exists(OpenFileDialog1.FileName) Then
            Dim Extention As String = New IO.FileInfo(OpenFileDialog1.FileName).Extension
            Select Case Extention.ToLower
                Case Is = ".jpg", Is = ".bmp", Is = ".gif"
                Case Else
                    MsgBox("Only JPG, BMP and GIF files are allowed. Thank you")
                    Exit Sub
            End Select
            Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
        End If
    End Sub


'Code to save picture (I stepped into the code and the frmAllottee.Pic1 is there)
Public Sub Save_Picture()
        Dim sql_command As SqlCommand
        Dim mStream As MemoryStream = New MemoryStream()
        'Dim mstream As New MemoryStream()
        frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) - This line gives the error
        Dim arrImage() As Byte = mstream.GetBuffer()
        mstream.Close()

        Dim Sql As String = "Insert into Alloc(Pic) VALUES(@Pic)"
        sql_command = New SqlClient.SqlCommand(Sql, Con)
        sql_command.Connection.Open()
        sql_command.Parameters.AddWithValue("@Pic1", arrImage)
        sql_command.ExecuteNonQuery()
        sql_command.Connection.Close()
    End Sub
4

2 回答 2

1

如果frmAllottee.Pic1.BackgroundImage为空,就会发生这种情况。

Image并且BackgroundImage不一样。

于 2013-06-17T13:33:45.267 回答
0
Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)

这里的这行代码与此代码不对应:

frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) 

您在保存图像时在图像中的 Pic1 中插入了图像,并且您选择了 BackgroundImage 而不是 Image

Dim Sql As String = "Insert into Alloc(Pic) VALUES(@Pic)"
    sql_command = New SqlClient.SqlCommand(Sql, Con)
    sql_command.Connection.Open()
    sql_command.Parameters.AddWithValue("@Pic1", arrImage)
    sql_command.ExecuteNonQuery()
    sql_command.Connection.Close()

@Pic 从插入到数据库应该与你的 @Pic1 添加时相同,即(两者都应该是 @Pic 或任何你喜欢的)我试过了,它可以工作

于 2017-08-29T01:28:02.260 回答