Results 1 to 40 of 64

Thread: Saving Images in Databases

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Saving Images in Databases

    C# version here.

    This question gets asked all the time so I thought an example was in order.

    Loading an image from a database field:
    VB.NET Code:
    1. Dim connection As New SqlConnection("connection string here")
    2. Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)
    3.  
    4. connection.Open()
    5.  
    6. Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
    7.  
    8. connection.Close()
    9.  
    10. Dim picture As Image = Nothing
    11.  
    12. 'Create a stream in memory containing the bytes that comprise the image.
    13. Using stream As New IO.MemoryStream(pictureData)
    14.     'Read the stream and create an Image object from the data.
    15.     picture = Image.FromStream(stream)
    16. End Using
    Saving an image to a database field:
    VB.NET Code:
    1. Dim connection As New SqlConnection("connection string here")
    2. Dim command As New SqlCommand("UPDATE MyTable SET Picture = @Picture WHERE ID = 1", connection)
    3.  
    4. 'Create an Image object.
    5. Using picture As Image = Image.FromFile("file path here")
    6.     'Create an empty stream in memory.
    7.     Using stream As New IO.MemoryStream
    8.         'Fill the stream with the binary data from the Image.
    9.         picture.Save(stream, Imaging.ImageFormat.Jpeg)
    10.  
    11.         'Get an array of Bytes from the stream and assign to the parameter.
    12.         command.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = stream.ToArray()
    13.     End Using
    14. End Using
    15.  
    16. connection.Open()
    17. command.ExecuteNonQuery()
    18. connection.Close()
    Please take note: this is example code only. Please don't paste it into your project and then ask why it doesn't work. Note also that while this code uses ExecuteScalar to get a single image's worth of data and ExecuteNonQuery to update a single existing record, the principles are the same no matter how your retrieving and saving your data. The important part is the MemoryStream. That is the link between the Byte array that gets stored in the database and the binary Image object in your VB app. For example, if you have 100 rows in a DataTable then you just use a MemoryStream for each row and assign the Byte array to the appropriate field of each row. You then just call the Update method of your DataAdapter as normal.

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