25 ธันวาคม 2554

VB.NET Save Image into SQL Server

บทความนี้ เป็นการนำเสนอวิธีการ การเก็บบันทึกรูปภาพเก็บไว้ในฐานข้อมูล SQL Server ด้วยภาษา Visual Basic.NET

สร้างฐานข้อมูลและตารางสำหรับเก็บข้อมูลรูปภาพ ดังนี้
(Create Database and Table)

- ให้ทำการสร้างฐานข้อมูล และตารางใน SQL Server ดังนี้

CREATE DATABASE myData
GO
CREATE TABLE [dbo].[tblImage](
[RowOrder] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [varchar](100) NULL,
[Image] [image] NULL,
CONSTRAINT [PK_tblImage] PRIMARY KEY CLUSTERED
(
[RowOrder] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

สร้างฟอร์มบันทึกรูปภาพ
(Create WindowsForm)
1. เปิดโปรแกรม Visual Studio 2010 แล้วทำการสร้าง Project ขึ้นมา จากนั้นทำการสร้างฟอร์ม โดยมี Control ต่าง ๆ ดังภาพ

1.Label
(name) = Label1
Text =
2.PictureBox
(name) = PictureBox1
SizeMode = PictureBoxSizeMode.StretchImage
3.Load Picture
(name) = btnLoad
Text = Load Picture
4.Save
(name) = btnSave
Text = Save
5.OpenFileDialog
(name) = OpenFileDialog1
FileName =





2. ให้ทำการ Imports Class เข้ามาใช้งานดังนี้

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

3. ประกาศตัวแปรเพื่อใช้ในฟอร์มดังนี้ โดยประกาศไว้ต่อจากบรรทัด Public Class ชื่อฟอร์ม

Public Class Form1
    Dim bm As Bitmap
    Dim fs As FileStream
    Dim fsImage As Byte()
...

4. ให้ทำการเข้าไปเขียนคำสั่งภายใน subroutine ขื่อ btnLoad_Click ของปุ่ม btnLoad ดังนี้
(คำสั่งในปุ่มนี้ จะเป็นการเปิดไฟล์รูปภาพจากในฮาร์ดดิสก์โดยใช้ OpenFileDialog
แล้วนำมาแสดงในคอนโทรล PictureBox1 รวมถึงอ่านไฟล์รูปภาพมาเก็บไว้ใน fsImage เพื่อนำไปใช้ในตอนบันทึกที่ปุ่ม Save)

With OpenFileDialog1
   .CheckFileExists = True
   .ShowReadOnly = False
   .Filter = "All Files|*.*|Picture Files|*.bmp;*.gif;*.jpg;*.png"
   .FilterIndex = 2
   If .ShowDialog = DialogResult.OK Then
      fs = New FileStream(.FileName.ToString(), FileMode.Open)
      fsImage = New Byte(fs.Length) {}
      fs.Read(fsImage, 0, fs.Length)
      fs.Close()
      bm = Image.FromFile(.FileName.ToString())
      PictureBox1.Image = bm
      Label1.Text = System.IO.Path.GetFileName(.FileName)
  End If
End With

5. ที่ปุ่ม Save ให้ทำการเข้าไปเขียนคำสั่งภายใต้ Subroutine ชื่อ btnSave_Click ดังนี้

If System.IO.File.Exists(Me.OpenFileDialog1.FileName) = False Then
   MessageBox.Show("File Not Found", "Error")
   Exit Sub
Else
   Dim strConn As String = "Data Source=.;Initial Catalog=myData;" & _ 
                           "Integrated Security=SSPI;"
   'strConn ให้เปลี่ยนค่าตามเครื่อง Server ของ SQL Server ที่ติดต่อ
       Dim Conn As New SqlConnection(strConn)
   Dim SqlString As String
   SqlString = "INSERT INTO tblImage(ImageName,Image) " & _
               " VALUES(@ImgName, @Img)"
   Dim cmd As SqlCommand = New SqlCommand(SqlString, Conn)
   Dim ImgName As SqlParameter = New SqlParameter("@ImgName", _
                                 System.Data.SqlDbType.VarChar, 100)
   ImgName.Value = Label1.Text.ToString()
   cmd.Parameters.Add(ImgName)

   Dim Img As SqlParameter = New SqlParameter("@Img", _
                             System.Data.SqlDbType.Image)
   Img.Value = fsImage
   cmd.Parameters.Add(Img)
   Try
      Conn.Open()
      cmd.ExecuteNonQuery()
      Conn.Close()
      MessageBox.Show("Save Image Complete", "Success")
   Catch ex As Exception
      MessageBox.Show(ex.Message.ToString(), "Error")
      Exit Sub
   End Try
End If

จากนั้นทำการรันฟอร์มที่เราสร้างแล้วทดสอบเปิดไฟล์รูปภาพแล้วทำการบันทึก

สร้างฟอร์มแสดงรูปภาพ
1. ให้ทำการสร้างฟอร์มเพิ่มขึ้นอีกหนึ่งฟอร์ม โดยคลิกที่เมนู Project เลือก Add Windows Form...
จะขึ้นหน้าต่าง Add New Item.. ให้เลือก Windows Form แล้วกำหนดชื่อฟอร์มตามต้องการ (Form2.vb)

2. ที่ฟอร์มให้ทำการลากคอนโทรล DataGridView และ คอนโทรล PictureBox มาวางไว้ดังภาพ

PictureBox   
(name) = PictureBox1
SizeMode = PictureBoxSizeMode.StretchImage







จากนั้นเข้าไปเขียนคำสั่ง ดังนี้ (copy เอาไปแทนได้เลย)

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Public Class Form2
    'strConn ให้เปลี่ยนค่าตามเครื่อง Server ของ SQL Server ที่ติดต่อ
    Private strConn As String = "Data Source=.;Initial Catalog=myData;" & _
                                       "Integrated Security=SSPI;"
    Private SqlString As String
    Private Conn As SqlConnection
    Private cmd As SqlCommand
    Private da As SqlDataAdapter
    Private ds As DataSet


    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            SqlString = "SELECT roworder,imagename FROM tblImage"
            Conn = New SqlConnection(strConn)
            Conn.Open()
            cmd = New SqlCommand(SqlString, Conn)
            da = New SqlDataAdapter(cmd)
            ds = New DataSet()
            da.Fill(ds, "tblImage")

            DataGridView1.DataSource = ds
            DataGridView1.DataMember = "tblImage"
            DataGridView1.ReadOnly = True

            DataGridView1.Columns(0).HeaderText = "Run No."
            DataGridView1.Columns(1).HeaderText = "Picture Name"

            'format GridView
            DataGridView1.GridColor = Color.Red
            DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None
            DataGridView1.BackgroundColor = Color.LightGray

            DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red
            DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow

            DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True]

            DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
            DataGridView1.AllowUserToResizeColumns = False

            DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque
            DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
            '
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString(), "Error")
        Finally
            If Conn.State = ConnectionState.Open Then
                Conn.Close()
            End If
        End Try
    End Sub

    Private Sub DataGridView1_SelectionChanged(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) _
            Handles DataGridView1.SelectionChanged

        Try
            SqlString = "select image from tblImage where roworder = @roworder"
            Conn = New SqlConnection(strConn)
            cmd = New SqlCommand(SqlString, Conn)

            Dim rdr As SqlDataReader = Nothing
            Dim imgData As Byte() = Nothing
            Dim row As Integer = DataGridView1.CurrentCellAddress.Y
            Dim roworder As String = DataGridView1.Rows(row).Cells(0).Value

            cmd.Parameters.AddWithValue("@roworder", roworder)
            Conn.Open()

            rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

            If rdr.Read() Then
                imgData = New Byte(rdr.GetBytes(0, 0, Nothing, 0, Integer.MaxValue) - 1) {}
                rdr.GetBytes(0, 0, imgData, 0, imgData.Length)
                Dim ms As New MemoryStream(imgData)
                PictureBox1.Image = Image.FromStream(ms)
            Else
                MessageBox.Show("No records found in the database.", "Warning")
            End If
        Catch ex As Exception
            PictureBox1.Image = Nothing
        Finally
            If Conn.State = ConnectionState.Open Then
                Conn.Close()
            End If
        End Try
    End Sub
End Class

เมื่อเราเรียกฟอร์มขึ้นมาทดสอบ จะปรากฎหน้าจอ คล้ายๆ ภาพตัวอย่างด้านล่าง











จากนี้ไปก็เป็นหน้าที่ของท่านผู้อ่านจะต้องนำไปไปประยุกต์ใช้งาน คงไม่ยากเกินความสามารถ
"I Believe in You"

Copyright(c) 2007 - 2022 by Kasem Kamolchaipisit.