As the title suggests, i am trying to pull a bitmap image stored in a table location with an OLEObject type to my picture box on the form. The code i am using is as following:

img_ProductPicture.Image = DS.Tables("LocationInfo").Rows(0).Item(5)

The error i am receiving is an InvalidCastException:
Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'

Am i missing something when pulling the image which will display it?

Thanks in advance for responses.

kvprajapati commented: ++rep. +11

Recommended Answers

All 5 Replies

dim barray() as byte  = DS.Tables("LocationInfo").Rows(0).Item(5)
Dim ms As New System.IO.MemoryStream(barray)
Dim img As Image = Image.FromStream(ms)

I will test that code when next have access to visual studio, i do not code on my Mac and still need to bootcamp it to windows 7 :) Will mark as solved etc if it works when i test :)

When using this code I encoutered an error on the following line:

Dim img As Image = Image.FromStream(ms)

Stating: Parameter is not valid.

Any idea why this is occuring?

>Error: Stating: Parameter is not valid.

Error says that you have invalid image data. Maybe image file is not stored correctly into the database.

Have a look at this attachment (How to save and load images) (Note: Manage database connection path)

I've use -sample- table having (ID Number, Info Ole) columns.

To write images

Dim bytes() As Byte = System.IO.File.ReadAllBytes("filename_here")

        Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder\Database4.mdb;Persist Security Info=True")

        Dim cmd As New OleDb.OleDbCommand("insert into sample (info) values (@info)", cn)
        cmd.Parameters.Add("@info", OleDb.OleDbType.Binary, bytes.Length).Value = bytes

        cn.Open()
        cmd.ExecuteNonQuery()
        cn.Close()

To read images

Dim adp As New OleDb.OleDbDataAdapter("select * from sample where id=2", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder\Database4.mdb;Persist Security Info=True")
        Dim ds As New DataSet
        adp.Fill(ds, "sample")

        Dim bytes() As Byte = ds.Tables("sample").Rows(0)("info")

        Dim img As Image = Image.FromStream(New System.IO.MemoryStream(bytes))
        PictureBox1.Image = img
commented: Very clear, example helped alot. +1

Thank you so much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.