0 Replies - 699 Views - Last Post: 04 July 2014 - 09:51 AM

#1 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3729
  • View blog
  • Posts: 13,019
  • Joined: 12-December 12

Save and load image from OLE Object field in MS Access

Posted 04 July 2014 - 09:51 AM

This code uses a PictureBox to display the image, it could be another control-type.

The image location is hard-coded, but an OpenFileDialog could be used.
Imports System.Data.OleDb

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
                                              "Data Source=C:\Users\Andrew\Documents\Pictures.accdb;" & _
                                              "Persist Security Info=False;")
        Dim cmd As New OleDbCommand("INSERT INTO tblPictures (Picture, Description) VALUES (?, 'testing')", conn)

        Using picture As Image = Image.FromFile("C:\Users\Andrew\Pictures\coyote.jpg")
            Using stream As New IO.MemoryStream
                picture.Save(stream, Imaging.ImageFormat.Jpeg)
                cmd.Parameters.Add("Picture", OleDbType.VarBinary).Value = stream.GetBuffer()
            End Using
        End Using

        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & _
                                              "Data Source=C:\Users\Andrew\Documents\Pictures.accdb;" & _
                                              "Persist Security Info=False;")
        Dim cmd As New OleDbCommand("SELECT Picture FROM tblPictures WHERE Description='testing'", conn)

        conn.Open()

        Dim pictureData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())

        conn.Close()

        Dim picture As Image = Nothing

        'Create a stream in memory containing the bytes that comprise the image.
        Using stream As New IO.MemoryStream(pictureData)
            'Read the stream and create an Image object from the data.
            picture = Image.FromStream(stream)
            PictureBox1.Image = picture
        End Using
    End Sub
End Class


This uses ExecuteScalar() because I am only retrieving a single picture (and a single field).

This post has been edited by andrewsw: 04 July 2014 - 01:54 PM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1