Database Answers Header

Storing Images in Access

Cows in Costa Rica QUESTION :How do I store Images in an Access Database ?
ANSWER :Use ADO and ASP
This answer is provided courtesy of David Mccarter who has an excellent Web Site for Visual Basic Tips and Tricks.

Using an Access database called db1.mdb with a table Table1 and
a field Field1 of the OLE type.
This is the Visual Basic code for storing an image :-

Dim a() As Byte, b As String, c, i, l, r

    Open "image.gif" For Binary As 1
    l = LOF(1)
    b = Space(l)
    Get #1, , b
    Close 1
    ReDim a(l)
    For i = 0 To l - 1
        a(i) = CByte(Asc(Mid(b, i + 1, 1)))
    Next i
    Set c = CreateObject("ADODB.Connection")
    c.Open "driver={Microsoft Access Driver (*.mdb)};dbq=db1.mdb"
    Set r = CreateObject("ADODB.RecordSet")
    r.Open "SELECT * FROM Table1", c, 2, 2
    If r.EOF Then
        r.addnew
    End If
    r(0) = a
    r.Update
    r.Close

This is the ASP code for retrieving the image :-

    <%
    Response.Buffer = true
    Response.Clear
    Response.Expires = 0
    Response.ContentType = "image/gif"
    Set c = Server.CreateObject("ADODB.Connection")
    c.Open "driver={Microsoft Access Driver *.mdb)};dbq=\inetpub\wwwroot\db1.mdb"
    Set r = CreateObject("ADODB.RecordSet")
    r.Open "SELECT * FROM Table1", c, 2, 2
    Response.BinaryWrite r(0)
    r.close
    Response.End
    %>

The only assumption is that the length of the image is not longer than the maximum variable size.
Otherwise the chunk-method should be used.

[ Home Page | Ask me a Question | Email | FAQs | History of Databases | Useful Links ]

© IceBreaker WebDesigns 2000