CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2008
    Posts
    90

    Question Problem in saving image to database from picturebox. VB.Net 2008. Framework 3.5.

    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:

    Code:
    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

  2. #2
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Problem in saving image to database from picturebox. VB.Net 2008. Framework 3.5.

    If there's an image in there, just DELETE it before replacing it. Let the user know, though.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  3. #3
    Join Date
    Sep 2008
    Posts
    90

    Exclamation Re: Problem in saving image to database from picturebox. VB.Net 2008. Framework 3.5.

    I have found the root of the problem but still couldn't get any solution. When we save the image using this line- 'pic.Image.Save(ms, pic.Image.RawFormat)' the image needs to be in its original format for the RawFormat() method to work properly. So when we click the Browse button, it's browsing an image into the picturebox in its original format. But when we
    retrieve the image from the database using arrays and streams, though we can view it but it's not in its original format and hence the above mentioned line in btnOk is throwing the exception.
    That's exactly the point and that's why inserting a new image is ok, update with a different image is ok but update with the same image is crashing. I think the key to solve it is while retrieving the image from the database if we can somehow convert it to its original format or some format that's recognizable by the RawFormat() method and then show it in the picturebox. In that way when we press btnOk for update, RawFormat() will get the original format of the picture and save it properly.
    I don't know how to do it practically or if there's some workaround. Can anybody make a solution out of this? Please assess on this topic and give your views. Regards.

  4. #4
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Problem in saving image to database from picturebox. VB.Net 2008. Framework 3.5.

    Something like this?


    Code:
    ' Imports System.IO;
    ' Imports System.Drawing.Imaging;
    
    Using ms As New MemoryStream()
        Me.pictureBox1.Image.Save(ms, ImageFormat.MemoryBmp)
        Dim imgBytes As [Byte]() = ms.GetBuffer()
    End Using
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured