Archive for the ‘VB’ Category

Images in Access or SQL database

Saturday, May 9th, 2009

Description: An example of how to image files in an Access or SQL database and later display in VB

There are two possibilities:

* Save the path (without the image data itself)
* Save the complete image

The first solution is probably the simpler solution, because only the pure path of the image file is stored. Second option is a bit expensive, but has the advantage that the image will be displayed again if the image file itself is not (more) on the computer is available. The big disadvantage here is that the database, depending on the number of stored images (and image size) may become very large.

Save the image information in a memo
To view the entire image in a database, it is best to use a database field of type memo. Such content can have a field up to 1.2 GByte of memory. This should then also for larger image files are sufficient.

To do this, use the following routine:

'Image in variable (string) read
Public Function wcReadPicture(strFilename As String) As String

 Dim intF As Integer
 Dim strInhalt As String

 intF = FreeFile
 Open strFilename For Binary As #intF
 strInhalt = Space$(Lof(intF))
 Get #intF, , strInhalt
 Close #intF

 wcReadPicture = strInhalt

End Function

Whenever you’re a picture in the database must therefore call on the above function:

'Save Image in Database
Table.Edit
Table("wcImage") = wcReadPicture(Your_Image_Path)
Table.Update

Image database and read in Picture / Image View Object
Now the image from the database later in a PictureBox or an Image object again, create a temporary file and save to the contents of the database image field. About LoadPicture statement, the image can then be displayed. Then the temporary file is deleted again.

And here the code:

'Load image from database and display
Public Sub wcShowPicture(Picture As Control, ByVal strInhalt As String) 

 Dim intF As Integer

 'Create a temporary image file
 intF = FreeFile
 Open App.Path & "\wcImage.tmp" For Output As #intF
 Print #intF, strInhalt;
 Close #intF

 'Picture
 Picture.Picture = LoadPicture(App.Path & "\wcImage.tmp")

 'Delete temporary file
 Kill App.Path & "\wcImage.tmp"

End Sub

The call of the procedure is then as follows:

wcShowPicture Picture1, Table("wcImage")

Happy Programming!! ;-)