Results 1 to 2 of 2

Thread: How to store image in sql db

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    May 2005
    Location
    London United Kingdom
    Posts
    334

    Question How to store image in sql db

    I am writting an employee form and the picture of the employee has to be stored in the sql db I am using, so any time a particular employee form is select his picture will show. I don't know how to go about it could anyone help me. I am able to insert and select other datas except the image. Thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to store image in sql db

    SQL Server has an 'image' column type. The data you assign to and retrieve from a column of that type is a Byte array. Here are some examples from my own VB 2005 code.

    Save an image from a PictureBox to a database field:
    VB Code:
    1. If Me.photoPicture.Image Is Me.emptyPhotoImage Then
    2.     saveCommand.Parameters("@Photo").Value = DBNull.Value
    3. Else
    4.     'Save the new photo.
    5.     Using photoData As New IO.MemoryStream
    6.         Me.photoPicture.Image.Save(photoData, Imaging.ImageFormat.Jpeg)
    7.         saveCommand.Parameters("@Photo").Value = photoData.GetBuffer()
    8.         photoData.Close()
    9.     End Using
    10. End If
    Load an image into a PictureBox from a database field:
    VB Code:
    1. If TypeOf memberReader("Photo") Is DBNull Then
    2.     Me.originalPhoto = Me.emptyPhotoImage
    3. Else
    4.     If Me.photoStream IsNot Nothing Then
    5.         Me.photoStream.Close()
    6.         Me.photoStream.Dispose()
    7.     End If
    8.  
    9.     'Load the photo.  The stream must be left open so that it can be accessed by the image at a later time.
    10.     Me.photoStream = New MemoryStream(DirectCast(memberReader("Photo"), Byte()))
    11.     Me.originalPhoto = Image.FromStream(photoStream)
    12. End If
    Note that the second example might look a bit odd. That's because you must keep the stream from which you create the Image open. If you don't you can encounter problems because GDI+ likes to go back to the stream at times to get information. That's why I check for an open stream and, if one is found, I close and dispose it before creating a new one. That new stream will remain open until it is closed and disposed when the next image is loaded using this same code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

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