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
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:
If Me.photoPicture.Image Is Me.emptyPhotoImage Then
saveCommand.Parameters("@Photo").Value = DBNull.Value
Else
'Save the new photo.
Using photoData As New IO.MemoryStream
Me.photoPicture.Image.Save(photoData, Imaging.ImageFormat.Jpeg)
saveCommand.Parameters("@Photo").Value = photoData.GetBuffer()
photoData.Close()
End Using
End If
Load an image into a PictureBox from a database field:
VB Code:
If TypeOf memberReader("Photo") Is DBNull Then
Me.originalPhoto = Me.emptyPhotoImage
Else
If Me.photoStream IsNot Nothing Then
Me.photoStream.Close()
Me.photoStream.Dispose()
End If
'Load the photo. The stream must be left open so that it can be accessed by the image at a later time.
Me.photoStream = New MemoryStream(DirectCast(memberReader("Photo"), Byte()))
Me.originalPhoto = Image.FromStream(photoStream)
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.