Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleStore and retrieve an image in an Access database
DescriptionThis example shows how to store and retrieve an image in an Access database in Visual Basic 6.
KeywordsAccess, image, picture, memo
CategoriesGraphics, 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()
    With Dlgs
        .Filter = "(*.bmp;*.jpg;*.gif;*.dat;*.pcx)| " & _
            "*.bmp;*.jpg;*.gif;*.dat;*.pcx|(*.psd)|*.psd|(*.All " & _
            "files)|*.*"
        .ShowOpen

        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
        Close #1

        'Add File To DB
        rs.AddNew
        rs!Img_name = FN
        rs!Image = FileBinary
        rs.Update

        'Refill List
        GetAllFiles
    End With
End Sub
 
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, _
        adLockPessimistic

    If rsSearchResults.EOF Then
        MsgBox "No records were found which match that " & _
            "phone number."
        'Don't change rs, since no match was found we'll
        ' stay on whatever
        'record was previously selected.
    Else
        '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
        'Write File
        Open App.Path & "\Temp.bmp" For Binary Access Write _
            As #1
        Put #1, , OutFile
        Close #1

        Image1.Picture = LoadPicture(App.Path & "\Temp.bmp")
    End If
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated