4 Replies - 7987 Views - Last Post: 22 August 2010 - 03:48 AM Rate Topic: -----

#1 priyamtheone  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 75
  • Joined: 02-September 08

Problem in saving image to database from picturebox. VB.Net 2008. Fram

Posted 20 August 2010 - 06:25 AM

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:

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



Is This A Good Question/Topic? 0
  • +

Replies To: Problem in saving image to database from picturebox. VB.Net 2008. Fram

#2 kasbaba  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 133
  • Joined: 03-November 08

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

Posted 20 August 2010 - 09:39 PM

'Create a new FileStream
Dim fs As New FileStream("C:\Pic.bmp", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)
Dim Data() As Byte = New [Byte](fs.Length) {}
fs.Read(Data, 0, fs.Length)

'Build the Insert Query
Dim InsertQ As String = "INSERT INTO Table1 (SName,DOB,Photo) Values ('ABC','17-JUN-1983',@StudentPhoto)"

'Execute the Insert Command
Dim myCommand As SqlClient.SqlCommand
myCommand = New SqlClient.SqlCommand(InsertQ, CON)
myCommand.Parameters.AddWithValue("@StudentPhoto", Data)
myCommand.ExecuteNonQuery()
myCommand.Dispose()

Let me know if this works for you !
Was This Post Helpful? 0
  • +
  • -

#3 priyamtheone  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 75
  • Joined: 02-September 08

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

Posted 21 August 2010 - 05:26 AM

Thanks kasbaba but my problem is not in Inserting but in Updating an existing image from the picturebox.
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.
Was This Post Helpful? 0
  • +
  • -

#4 kasbaba  Icon User is offline

  • D.I.C Head

Reputation: 28
  • View blog
  • Posts: 133
  • Joined: 03-November 08

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

Posted 22 August 2010 - 01:54 AM

Here is the code to convert Image(stored in the database) to Image format recognized by picture boxes.

        Dim RS0 As SqlClient.SqlDataReader = Nothing
        Dim SQLComm0 As New SqlClient.SqlCommand
        SQLComm0 = CON.CreateCommand
        SQLComm0.CommandText = "Select * from StudentRecord where StudentID=1"
        RS0 = SQLComm0.ExecuteReader
        If RS0.Read = True Then
            'Load photo
            msgbox RS0("StudentName")
            If IsDBNull(RS0("StudentPhoto")) = False Then
                Dim bits As Byte() = CType(RS0("StudentPhoto"), Byte())
                Dim memorybits As New MemoryStream(bits)
                Dim bitmap As New Bitmap(memorybits)
                PictureBox1.Image = bitmap
            End If
        End If
        RS0.Close()

Was This Post Helpful? 1
  • +
  • -

#5 ranbir  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 27
  • Joined: 04-June 10

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

Posted 22 August 2010 - 03:48 AM

hi priyamtheone!
I got the same problem but i used the following code to solve my problem.

Dim  tempImgeFilename as string="c:\tmp.tmp"

private sub show_record()
         picBOX1.Image = getPhoto(dvElectors.Item(dgSelectedIndex).Row("Photo"), TempImageFileName)
end sub

 Public Function getPhoto(ByVal PhotoData As Object, ByVal TempFileName As String) As Bitmap
        If IsDBNull(PhotoData) Then Return Nothing
        Dim Bimages As Byte() = CType(PhotoData, Byte())
        If Bimages.Length = 0 Then Return Nothing
        Dim photo As Bitmap
        Dim mstream As New IO.MemoryStream(Bimages.Length)
        Dim outputwriter As IO.BinaryWriter = New IO.BinaryWriter(mstream)
        With outputwriter
            .Write(Bimages, 0, Bimages.Length)
            .Flush()
            photo = Image.FromStream(mstream)
            .Close()
        End With
        outputwriter.Close()
        mstream.Close()

        Try
            If IO.File.Exists(TempFileName) Then File.Delete(TempFileName)
        Catch
        End Try
        Dim fs As IO.FileStream = New IO.FileStream(app_path() & TempFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
        fs.Write(Bimages, 0, Bimages.Length - 1)
        fs.Flush()
        fs.Dispose()
        Return photo
    End Function

Private sub btnSave.clicked( ...............) Handles BtnSave.clicked
            Dim bmp As Bitmap = Image.FromFile( TempImageFileName)
            Dim ms As New IO.MemoryStream
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
            Dim bytes() As Byte = ms.GetBuffer()

'HERE THE CODE FOR ADDING PARAMETERS AND SAVING TO THE DATABASE
' ..............
end sub




View Postpriyamtheone, on 20 August 2010 - 05:25 AM, said:

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:

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


This post has been edited by ranbir: 22 August 2010 - 03:51 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1