1 Previous Next 

Insert an image (picture, blob) in a database in the most simple way.


Often is asked in the forums how to insert an image in the database. We did not have the most simplest way in our website. Therefore this 2012 sample. Be aware it is made with VB10SP1 in VB11 style.
Option Explicit On
Option Strict On
Option Infer On
Imports System.Data.SqlClient
'Sample made with VB10SP1 for earlier versions add Byval while the ID is an integer autoidentifier
Public Class Form1
    Private ImageToUse As Image
    Private Sub Form1_Load(sender As Object, e As EventArgsHandles MyBase.Load
        Button1.Text = "Get Image"
        Button2.Text = "Save Image to DataBase"
        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
    End Sub
    Private Sub Button2_Click(sender As Object, e As EventArgsHandles Button2.Click
        'Error catching not implemented in this sample
        Using con As New SqlConnection("Data Source=YourServerName;Initial Catalog=TestDataBase;Integrated Security=True")
            Using com As New SqlCommand("Insert into TestTable(Picture) values (@1)", con)
                Using ms As New IO.MemoryStream
                    ImageToUse.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
                    Dim byteArray = ms.ToArray
                    com.Parameters.AddWithValue("@1", byteArray)
                    con.Open()
                    com.ExecuteNonQuery()
                End Using
            End Using
        End Using
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgsHandles Button1.Click
        Using OFD As New OpenFileDialog With {.Filter = "Jpg (*.jpg)|*.jpg"}
            If OFD.ShowDialog = DialogResult.OK Then
                ImageToUse = Image.FromFile(OFD.FileName)
                PictureBox1.Image = ImageToUse
            End If
        End Using
    End Sub
End Class



1 Previous Next