Question Problem in saving image to database from picturebox

priyamtheone

Well-known member
Joined
Sep 20, 2007
Messages
96
Programming Experience
Beginner
Hi there,
I have a form containing a listbox showing a list of image names. It's bound
to the database table. When an image name is clicked it shows the image and
imagename in a picturebox and textbox respectively. When no image is selected
in the listbox, a new record can be inserted by browsing a new image in the
picturebox by an openfiledialog, writing the imagename in the textbox and
pressing the OK button. When an image is already selected, the record can be
updated by pressing the same OK button. The data is saved into MSSQL Server
2005. Corresponding table fields are Keycode int autono,
logoname nvarchar(50), logo image.
Now the problem, when I insert a new data with an image everything goes fine
but whenever I try to update an existing data with an image it throws an
exception- 'A generic error occurred in GDI+.' at the following line-
'pic.Image.Save(ms, pic.Image.RawFormat)'. Surprisingly when I update an
existing data without any image in the picturebox no exception is generated.
I have crossed checked it and seems that the problem is just at one point-
'Updating the image from the picturebox'.
I'm almost done all throughout but stuck to this particular point. Please help. Regards.

My code to insert/update the data by OK button and to populate it by listbox
doubleclick follows:

VB.NET:
Private ms As MemoryStream
Private arrImage() As Byte
Private conn As SqlConnection
Private cmd As SqlCommand

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	'Method to bind listbox.
	BindListBox(lst, "Select Keycode,LogoName from tbltest", "Logoname", "keycode")
        Tag = "Insert"
End Sub

Private Sub lst_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lst.DoubleClick
        Dim dr As SqlDataReader

        dr = CreateReader("Select LogoName,logo from tblTest where keycode=" & lst.SelectedValue)
        If dr.Read Then
            txtLogoName.Text = vbNullString & dr("Logoname")
            If Not IsDBNull(dr("Logo")) Then
                arrImage = CType(dr("Logo"), Byte())
                ms = New MemoryStream(arrImage)
                pic.Image = Image.FromStream(ms)
                ms.Close()
            Else
                pic.Image = Nothing
                pic.Invalidate()
            End If
            Tag = "Update"
        End If
        dr.Close()
        closeconnection()
        arrImage = Nothing
        ms = Nothing
End Sub

Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Dim com As SqlCommand
        Dim strSql As String

        If Tag = "Insert" Then
            strSql = "Insert into tbltest (logoname,logo) values ('" & Trim(txtLogoName.Text) & "',@Logo)"
        Else
            strSql = "Update tbltest set logoname='" & Trim(txtLogoName.Text) & "',Logo=@Logo Where keycode=" & lst.SelectedValue
        End If

        com = CreateCommand(strSql)
        com.Parameters.Add(New SqlParameter("@Logo", SqlDbType.Image))
        If Not pic.Image Is Nothing Then
            ms = New MemoryStream()
            pic.Image.Save(ms, pic.Image.RawFormat)
            arrImage = ms.GetBuffer
            ms.Close()
            com.Parameters("@Logo").Value = arrImage
        Else
            com.Parameters("@Logo").Value = DBNull.Value
        End If

        If com.ExecuteNonQuery = 1 Then
            closeconnection()
            BindListBox(lst, "Select Keycode,LogoName from tbltest", "Logoname", "keycode")
            pic.Image = Nothing
            pic.Invalidate()
            txtLogoName.Clear()
            Tag = "Insert"
        End If


        arrImage = Nothing
        ms = Nothing
        strSql = Nothing
End Sub

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        With dlg
            .Filter = "All Files|*.*|Bitmap|*.bmp|GIF|*.gif|Icon|*.ico|JPEG|*.jpg|PNG|*.png"
            .FilterIndex = 5
        End With

        If dlg.ShowDialog() = DialogResult.OK Then pic.Image = Image.FromFile(dlg.FileName)
End Sub

Public Sub setconnection()
        Try
            conn = New SqlConnection("Data Source=MyServer;Initial Catalog=TestDB;User Id=sa;Password=;")
            conn.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
End Sub

Public Sub closeconnection()
    	conn.Close()
End Sub

Public Function CreateCommand(ByVal query As String) As SqlCommand
    	setconnection()
    	Dim command As New SqlCommand(query, conn)
    	Return command
End Function

Public Function CreateReader(ByVal query As String) As SqlDataReader
    	Dim reader As SqlDataReader
    	setconnection()
    	cmd = CreateCommand(query)
    	reader = cmd.ExecuteReader()
    	Return reader
End Function
 
Last edited:

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,726
Location
Sydney, Australia
Programming Experience
10+
These generic GDI+ errors can be hard to diagnose. The first thing I notice is that you aren't disposing your Images when you're done with them, which is a problem, even if it's not the cause. Make sure that, each time you set the Image property of the PictureBox, you dispose the current Image, if there is one. Implement that change and then see if your issue persists.
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,604
Location
Norway
Programming Experience
10+
pic.Image = Image.FromStream(ms)
ms.Close()
This is something that should result in error next time image is accessed, for example when the window repaints, or if your try to save it. If you look at the FromStream help it explains that the source stream must be open for reading for the lifetime of the image object.
ms = New MemoryStream()
pic.Image.Save(ms, pic.Image.RawFormat)
arrImage = ms.GetBuffer
ms.Close()
Here you should use a private stream. Also you should use ToArray to get the bytes of the image, GetBuffer returns the buffer of the MemoryStream which includes unused buffer bytes.
 
Top Bottom