Simpan Image Menggunakan VB.NET Dengan SQL Server

 

Berikut adalah cara simpan image di VB.net pada SQL Server

1. Buat database dan table

1.1. Database : dbimage

create database dbimage;

1.2. Table : tblimage

CREATE TABLE [dbo].[tbl_images](

 [nama] [varchar](50) NULL,

 [gambar] [image] NULL

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


2. Design Tampilan VB.Net : frmSimpanImage.vb

Componen :

  • Datagridview
  • Textbox
  • 2 Button
  • Image



3. Buat module : mdlKoneksi.vb

Imports System.Data.SqlClient

Module mdlKoneksi

    Public konek As SqlConnection

    Sub konekDB()

        Try

            konek = New SqlConnection _

                ("Data Source=DESKTOP-5VBP3C9\SQLEXPRESS;" _

            + "Initial Catalog=dbimage;Integrated Security=True")

            konek.Open()

        Catch ex As Exception

            MsgBox("konek Kedatabase Bermasalah,  Periksa koneksi ")

        End Try

    End Sub

End Module


4. Tambahkan Code pada frmSimpanImage.vb 

Imports System.Data.SqlClient

Imports System.IO

Sub TampilkanData()

    konekDB()

    Dim dA As SqlDataAdapter = New SqlDataAdapter _

    ("SELECT nama,gambar FROM tblimages", konek)

    Dim dS As DataSet = New DataSet

    dS.Clear()

    dA.Fill(dS, "tbl_images")

    DataGridView1.DataSource = (dS.Tables("tblimages"))

    dA.Dispose()

    konek.Close()

End Sub


5. Tambahkan code pada button1_click : untuk mengambil gambar menggunakan opendialog

Private Sub Button1_Click(sender As Object, e As EventArgs) _

    Handles Button1.Click

    If OpenFileDialog1.ShowDialog() =

        Windows.Forms.DialogResult.OK Then

        PictureBox1.BackgroundImage =

            Image.FromFile(OpenFileDialog1.FileName)

        PictureBox1.BackgroundImageLayout =

            ImageLayout.Zoom

    End If

End Sub


6.  Tambahkan code pada button2_click : untuk menyimpan image

Private Sub Button2_Click(sender As Object, e As EventArgs) _

    Handles Button2.Click

    If TextBox1.Text = "" Then

        MsgBox("Isikan nama Gambar")

    Else

        konekDB()

        Dim CMD As SqlCommand

        Dim SQL As String

        SQL = "INSERT INTO tblimages VALUES(@nama, @gambar) "

        CMD = New SqlCommand(SQL, konek)

        CMD.Parameters.AddWithValue("@nama", TextBox1.Text)

        Dim MemoryStream As New MemoryStream

        PictureBox1.BackgroundImage.Save(MemoryStream,

        PictureBox1.BackgroundImage.RawFormat)

        Dim Dgambar As Byte() = MemoryStream.GetBuffer

        Dim Images As New SqlParameter("@gambar", SqlDbType.Image)

        Images.Value = Dgambar

        CMD.Parameters.Add(Images)

        CMD.ExecuteNonQuery()

        MsgBox("Gambar Berhasil Disimpan")

        TextBox1.Clear()

        CMD.Dispose()

        konek.Close()

        TampilkanData()

    End If

End Sub


7.  Tambahkan code pada form_load

Private Sub frmSimpanImages_Load(sender As Object, e As EventArgs) _

    Handles MyBase.Load

    TampilkanData()

End Sub


Jalankan: