Vb.net – How to store and retrieve images in sql server database with vb.net using picturebox

vb.net

Can someone please tell me the easiest technique to store and retrieve image in a SQL Server database with vb.net.

A very important consideration requirement:

Well, the application in vb.net seems to have a database which can accessed by the LAN computers so the SQL Server 2005 database allows remote computers to share its database once the other computer application requests database from the server.

So, every other computer has to store and retrieve images in SQL Server 2005. For example, comp1 has to store images taken into the server and retrieve it like tableadapter.

I am using bindings and tableadapters to store the details in database and retrieving information from db. Please if you have code or anything which is working for me, please post it here…

Please share with me how to store image and retrieve it SQL Server through vb.net provided there's LAN computers who are also sharing the SQL Server database.

Please, if anyone has a knowledge about this stuff, I would really appreciate it.

With all my heart, I request you consider my issue, please.

Best Regards,

Hosseinel

Best Answer

Let's have a table containing images (instead of max you can use desired size):

CREATE TABLE dbo.STORED_IMAGES
     (
     ID int NOT NULL  IDENTITY (1, 1),
     Img varbinary(MAX) NULL
     ) 

Storing image:

Dim CMD As New SqlClient.SqlCommand("insert into STORED_IMAGES(Img) values(@Img)",cn)
CMD.Parameters.Add("@Img", SqlDbType.VarBinary, Integer.MaxValue).Value = ReadFile(Path)

Function for reading file:

Private Function ReadFile(sPath As String) As Byte()
        Dim data As Byte() = Nothing
        Dim fInfo As New IO.FileInfo(sPath)
        Dim numBytes As Long = fInfo.Length
        Using fStream As New IO.FileStream(sPath, IO.FileMode.Open, IO.FileAccess.Read)
            Dim br As New IO.BinaryReader(fStream)
            data = br.ReadBytes(CInt(numBytes))
        End Using
        Return data
    End Function

Getting file from DB:

Dim fcmd As New SqlCommand("select Img from STORED_IMAGES where ID=@ID", cn)
fcmd.Parameters.Add("@ID", SqlDbType.Int).Value = 3 'e.g.
Dim bytes As Byte() = fcmd.ExecuteScalar

I suppose that with tableadapters your datatable will contain column with type Byte().

Related Topic