Loading an Image

arvindmewara

New member
Joined
May 26, 2008
Messages
3
Programming Experience
Beginner
hi all,

i want to load an image from ms access database in vb.net picture box control(window form.)

how to do this?

thanks
arvind
 
Hello Arvind,

You can use the given code to show images from a MSAccess Database table
into Windows Picture Box. To implement the given code, drop a picture box
and two buttons on a Windows form. Two buttons have been used to move
back and forward to display the images from the table.


BEGIN CODE

VB.NET:
Imports System.Data.OleDb
Imports System.IO

Public Class Form1

    Dim conn As New OleDbConnection
    Dim DA As OleDbDataAdapter
    Dim DS As New DataSet
    Dim counter As Integer


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Nwind.mdb;User Id=admin;Password=;"

        DA = New OleDbDataAdapter("Select Photo from Employees", conn)

        DA.Fill(DS)

        counter = 0

        Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        PictureBox1.Image = GetImageFromByteArray(DS.Tables(0).Rows.Item(counter).Item(0))

        If counter < Me.DS.Tables(0).Rows.Count - 1 Then

            counter += 1

        End If


    End Sub

    Private Function GetImageFromByteArray(ByVal picData As Byte()) As Image
        If picData Is Nothing Then
            Return Nothing
        End If

        ' is this is an embedded object? 
        Dim bmData As Integer = IIf((picData(0) = 21 AndAlso picData(1) = 28), 78, 0)

        ' load the picture 
        Dim img As Image = Nothing
        Try
            Dim ms As New MemoryStream(picData, bmData, picData.Length - bmData)
            img = Image.FromStream(ms)
        Catch
        End Try

        ' return what we got 
        Return img

    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        PictureBox1.Image = GetImageFromByteArray(DS.Tables(0).Rows.Item(counter).Item(0))

        If counter > 0 Then

            counter -= 1

        End If

    End Sub
End Class

END CODE

MSAccess will return the images in the form of byte arrays. We need to
convert these bytes into Image format. GetImageFromByteArray() does the
same in the above code. It takes the arrray of bytes and convert them into
images which can then easily set into a Picture box.

I hope this will help.

Regards,

Allen Smith
ComponentOne LLC
www.componentone.com
 

Latest posts

Back
Top