Please help me how to store and retrieve images in a picture box avoiding creating a temporary image file.
Thanks.
Printable View
Please help me how to store and retrieve images in a picture box avoiding creating a temporary image file.
Thanks.
I am using the following code and it works fine. You can store and retrieve images into a database using a storedprocedure just as you would do with any other kind of field, but you gotta transform the images into byte arrays within your code.
Retrieve from database (dsrow is the datarow containing the image and Image is the field in that row)
Store in Database (dlgOpen is an open file dialog control):Code:' Photo
Dim MyByteArray() As Byte
MyByteArray = dsrow.Item("Image")
If MyByteArray.Length > 0 Then
Dim myStream As MemoryStream = New MemoryStream(MyByteArray, True)
myStream.Write(MyByteArray, 0, MyByteArray.Length)
MyPictureBox.Image = New Bitmap(myStream)
myStream.Close()
Else
MyPictureBox.Image = Nothing
End If
Code:MyByteArray = LoadNewImage(dlgOpen.FileName)
If MyByteArray.Length > 0 Then
'' Create new MemoryStream and write the byte array info into the stream
Dim myStream As MemoryStream = New MemoryStream(MyByteArray, True)
myStream.Write(MyByteArray, 0, MyByteArray.Length)
'' Create new bitmap
MyPictureBox.Image = New Bitmap(myStream)
myStream.Close()
End If
dsrow.Item("Image")=MyByteArray
Finally, the function to load new images into your picturebox:
Code:Public Function LoadNewImage(ByVal MyFileName As String) As Byte()
' make sure the file is JPEG or GIF
Dim testFile As System.IO.FileInfo = New System.IO.FileInfo(MyFileName)
If Not String.Compare(testFile.Extension, ".GIF", True) = 0 _
And Not String.Compare(testFile.Extension, ".JPG", True) = 0 _
And Not String.Compare(testFile.Extension, ".JPEG", True) = 0 _
And Not String.Compare(testFile.Extension, ".BMP", True) = 0 Then
MessageBox.Show("You have selected a non supported format." & vbCrLf & _
"Please, select a JPG, GIF or BMP image.", "Load Image")
Return Nothing
End If
'' Create a new stream to load this photo into
Dim myStream As FileStream = New FileStream(MyFileName, FileMode.Open, FileAccess.Read)
'' Create a buffer to hold the stream of bytes
Dim myImageBuffer(myStream.Length) As Byte
'' Read the bytes from this stream and put it into the image buffer
myStream.Read(myImageBuffer, 0, Convert.ToInt32(myStream.Length))
'' Close the stream
myStream.Close()
Return myImageBuffer
End Function
Thanks.
We'll try.