locked
Saving a picture RRS feed

  • Question

  • I have a picture box that i can draw in using mousePath.AddLine This works well but now i need to save the image into a datadase.
    Can anyone let me know how to do this?
    Wednesday, August 31, 2005 12:08 PM

Answers

  • MS Sample:

    Data Access - Read and Write Images from a Database



    ' Handles the Save button click event, allowing the user to save the image

    ' viewed in the PictureBox to the database.

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

    ' PREPARE DATA TO BE PASSED TO DATABASE:

    ' You only need to save the filename, not the entire path. Therefore,

    ' Split the path, creating an array of strings. Make sure you pass in

    ' the delimiter. Then reverse the array so that you can assign the

    ' first string in the array to the SQL parameter.

    Dim arrFilename() As String = Split(lblFilePath.Text, "\")

    arrFilename.Reverse(arrFilename)

    ' The SQL Server Image datatype is a binary datatype. Therefore, to save

    ' it to the database you must convert the image to an array of bytes. You

    ' could use a FileStream object to open the image file and then read it to

    ' the stream, but a MemoryStream with the Image.Save method is a bit easier.

    Dim ms As New MemoryStream()

    PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)

    Dim arrImage() As Byte = ms.GetBuffer

    ' Close the stream object to release the resource.

    ms.Close()

    ' Display a status message saying that we're attempting to connect.

    ' This only needs to be done the very first time a connection is

    ' attempted. After we've determined that MSDE or SQL Server is

    ' installed, this message no longer needs to be displayed.

    Dim frmStatusMessage As New frmStatus()

    If Not didPreviouslyConnect Then

    frmStatusMessage.Show("Connecting to SQL Server")

    End If

    ' Attempt to connect to the local SQL server instance, and a local

    ' MSDE installation (with Northwind).

    Dim isConnecting As Boolean = True

    While isConnecting

    Try

    ' The SqlConnection class allows you to communicate with SQL Server.

    ' The constructor accepts a connection string as an argument. This

    ' connection string uses Integrated Security, which means that you

    ' must have a login in SQL Server, or be part of the Administrators

    ' group for this to work.

    Dim northwindConnection As New SqlConnection(connectionString)

    Dim strSQL As String = _

    "INSERT INTO Picture (Filename, Picture)" & _

    "VALUES (@Filename, @Picture)"

    ' A SqlCommand object is used to execute the SQL statement.

    Dim cmd As New SqlCommand(strSQL, northwindConnection)

    With cmd

    ' Add parameters required by SQL statement. PictureID is an

    ' identity field (in Microsoft Access, an AutoNumber field),

    ' so you only need to pass values for the two remaining fields.

    .Parameters.Add(New SqlParameter("@Filename", _

    SqlDbType.NVarChar, 50)).Value = arrFilename(0)

    .Parameters.Add(New SqlParameter("@Picture", _

    SqlDbType.Image)).Value = arrImage

    End With

    ' Open the connection, execute the command, and close the

    ' connection. It is more efficient to ExecuteNonQuery when data

    ' is not being returned.

    northwindConnection.Open()

    cmd.ExecuteNonQuery()

    northwindConnection.Close()

    ' Data has been successfully submitted, so break out of the loop

    ' and close the status form.

    isConnecting = False

    didPreviouslyConnect = True

    frmStatusMessage.Close()

    MessageBox.Show(arrFilename(0) & " saved to the database.", _

    "Image Save Status", MessageBoxButtons.OK, _

    MessageBoxIcon.Information)

    Catch sqlExc As SqlException

    MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _

    MessageBoxButtons.OK, MessageBoxIcon.Error)

    Exit While

    Catch exc As Exception

    If connectionString = SQL_CONNECTION_STRING Then

    ' Couldn't connect to SQL Server. Now try MSDE.

    connectionString = MSDE_CONNECTION_STRING

    frmStatusMessage.Show("Connecting to MSDE")

    Else

    ' Unable to connect to SQL Server or MSDE

    frmStatusMessage.Close()

    MessageBox.Show(CONNECTION_ERROR_MSG, _

    "Connection Failed!", MessageBoxButtons.OK, _

    MessageBoxIcon.Error)

    End

    End If

    End Try

    End While

    End Sub




     
    Wednesday, August 31, 2005 3:23 PM

All replies

  • MS Sample:

    Data Access - Read and Write Images from a Database



    ' Handles the Save button click event, allowing the user to save the image

    ' viewed in the PictureBox to the database.

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

    ' PREPARE DATA TO BE PASSED TO DATABASE:

    ' You only need to save the filename, not the entire path. Therefore,

    ' Split the path, creating an array of strings. Make sure you pass in

    ' the delimiter. Then reverse the array so that you can assign the

    ' first string in the array to the SQL parameter.

    Dim arrFilename() As String = Split(lblFilePath.Text, "\")

    arrFilename.Reverse(arrFilename)

    ' The SQL Server Image datatype is a binary datatype. Therefore, to save

    ' it to the database you must convert the image to an array of bytes. You

    ' could use a FileStream object to open the image file and then read it to

    ' the stream, but a MemoryStream with the Image.Save method is a bit easier.

    Dim ms As New MemoryStream()

    PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)

    Dim arrImage() As Byte = ms.GetBuffer

    ' Close the stream object to release the resource.

    ms.Close()

    ' Display a status message saying that we're attempting to connect.

    ' This only needs to be done the very first time a connection is

    ' attempted. After we've determined that MSDE or SQL Server is

    ' installed, this message no longer needs to be displayed.

    Dim frmStatusMessage As New frmStatus()

    If Not didPreviouslyConnect Then

    frmStatusMessage.Show("Connecting to SQL Server")

    End If

    ' Attempt to connect to the local SQL server instance, and a local

    ' MSDE installation (with Northwind).

    Dim isConnecting As Boolean = True

    While isConnecting

    Try

    ' The SqlConnection class allows you to communicate with SQL Server.

    ' The constructor accepts a connection string as an argument. This

    ' connection string uses Integrated Security, which means that you

    ' must have a login in SQL Server, or be part of the Administrators

    ' group for this to work.

    Dim northwindConnection As New SqlConnection(connectionString)

    Dim strSQL As String = _

    "INSERT INTO Picture (Filename, Picture)" & _

    "VALUES (@Filename, @Picture)"

    ' A SqlCommand object is used to execute the SQL statement.

    Dim cmd As New SqlCommand(strSQL, northwindConnection)

    With cmd

    ' Add parameters required by SQL statement. PictureID is an

    ' identity field (in Microsoft Access, an AutoNumber field),

    ' so you only need to pass values for the two remaining fields.

    .Parameters.Add(New SqlParameter("@Filename", _

    SqlDbType.NVarChar, 50)).Value = arrFilename(0)

    .Parameters.Add(New SqlParameter("@Picture", _

    SqlDbType.Image)).Value = arrImage

    End With

    ' Open the connection, execute the command, and close the

    ' connection. It is more efficient to ExecuteNonQuery when data

    ' is not being returned.

    northwindConnection.Open()

    cmd.ExecuteNonQuery()

    northwindConnection.Close()

    ' Data has been successfully submitted, so break out of the loop

    ' and close the status form.

    isConnecting = False

    didPreviouslyConnect = True

    frmStatusMessage.Close()

    MessageBox.Show(arrFilename(0) & " saved to the database.", _

    "Image Save Status", MessageBoxButtons.OK, _

    MessageBoxIcon.Information)

    Catch sqlExc As SqlException

    MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _

    MessageBoxButtons.OK, MessageBoxIcon.Error)

    Exit While

    Catch exc As Exception

    If connectionString = SQL_CONNECTION_STRING Then

    ' Couldn't connect to SQL Server. Now try MSDE.

    connectionString = MSDE_CONNECTION_STRING

    frmStatusMessage.Show("Connecting to MSDE")

    Else

    ' Unable to connect to SQL Server or MSDE

    frmStatusMessage.Close()

    MessageBox.Show(CONNECTION_ERROR_MSG, _

    "Connection Failed!", MessageBoxButtons.OK, _

    MessageBoxIcon.Error)

    End

    End If

    End Try

    End While

    End Sub




     
    Wednesday, August 31, 2005 3:23 PM
  • This is good. But any chance of doing it in VB 2005 beta?
    i have tried but have failed.

    Monday, September 5, 2005 4:29 PM
  • Should work in 05 also....

    where did it fail...
    what code are you using...

    Monday, September 5, 2005 7:58 PM
  • Microsoft has provided some pretty simple mechanisms for this.


    Here is a working example and I need to discuss this a bit with you after the code.

    Private Sub cbGo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbGo.Click

    ' Copy the existing image from picturebox 1 to an image in memory

    ' The reason for this will become apparent later

    Dim pb1 As New PictureBox

    pb1.Size = New Size(32, 32)

    pb1.Location = New Point(100, 100)

    Me.Controls.Add(pb1)

    Dim img As Image

    img = System.Drawing.Image.FromFile("H:\Integration\MyToolBar\Art\happytoolbar.gif")

    pb1.Image = img

    pb1.Image.Save("c:\f.dat", System.Drawing.Imaging.ImageFormat.Gif)

    Dim pb2 As New PictureBox

    pb2.Size = New Size(32, 32)

    pb2.Location = New Point(100, 150)

    Me.Controls.Add(pb2)

    pb2.Image = System.Drawing.Image.FromFile("c:\f.dat")

    MsgBox("Here you are", MsgBoxStyle.OKOnly, "Done")

    End

    End Sub


    **Sigh** a simple read or a simple write are fine. This code could be much simpler but to be honest I had problems with vs2005 Beta-2.

    The documentation specificies that the files are locked until the images are disposed of and that does seem to be the case.

    However, disposing of the image seems to corrupt some internal structures of the image because it loses it ability to be re-useable, even when I built them dynamically as I did.

    Returning exceptions are very vague like GDi unspecified error or bad parameter but where the parameter not decribed.

    Anyway, simple means are there made simple by what appears to be bugs.

    The "End" at the end of the routine is there for a purpose. This subroutine will not run twice and no matter how many different combinations I tried, I couldn't get it to run twice between the file locking and the bugs.

    Enjoy!

    Tuesday, September 6, 2005 2:37 AM
  • hi there,

    i have succesfully store the image into the database using the coding as you shown, but i having problem getting back the binary data from the database show it back in the picture box.

    can you show me example coding on how to read back the picture

    anyway, the above coding really help me a lot, thanks very much
    Wednesday, November 9, 2005 7:25 PM
  •  

    And what datatype in the database table should I use?

    What about to save a document in the same table?

     

    Great example, thanks.

    Wednesday, September 19, 2007 12:22 AM