|Title||Store and retrieve an image in an Access database|
|Description||This example shows how to store and retrieve an image in an Access database in Visual Basic 6.|
|Keywords||Access, image, picture, memo|
|Categories||Graphics, Database, Office|
Thanks to Gamal.
The rs Recordset is attached to a table that contains a Memo field named Image. When you click the program's Add button, the following code displays an Open File dialog. If you select a file, it reads the file into a String variable named FileBinary. It creates a new database record and sets its Image field to this string.
Private Sub Command1_Click()
.Filter = "(*.bmp;*.jpg;*.gif;*.dat;*.pcx)| " & _
"*.bmp;*.jpg;*.gif;*.dat;*.pcx|(*.psd)|*.psd|(*.All " & _
If .FileName = "" Then Exit Sub
FN = .FileTitle
'Open File And Read as Binary
Open .FileName For Binary Access Read As #1
FileBinary = Space(LOF(1))
Get #1, , FileBinary
'Add File To DB
rs!Img_name = FN
rs!Image = FileBinary
When it needs to display an image from the database, the program selects the record's Image field into a string, writes it into a temporary file, and loads the file.
Function ViewPic(FName As String)
'View Pic From DB
Dim OutFile As String
Dim strSql As String
Dim rsSearchResults As ADODB.Recordset
strSql = ""
strSql = "select * from Pic where Img_name = '" & FName _
'Open a recordset to hold the search results.
Set rsSearchResults = New ADODB.Recordset
rsSearchResults.Open strSql, db, adOpenStatic, _
If rsSearchResults.EOF Then
MsgBox "No records were found which match that " & _
'Don't change rs, since no match was found we'll
' stay on whatever
'record was previously selected.
'Set the form's current recordset to hold only the
' search results.
Set rs = rsSearchResults
If Dir(App.Path & "\Temp.bmp") <> "" Then Kill _
App.Path & "\Temp.bmp"
OutFile = rs!Image
Open App.Path & "\Temp.bmp" For Binary Access Write _
Put #1, , OutFile
Image1.Picture = LoadPicture(App.Path & "\Temp.bmp")