Senin, 30 Juli 2012

Display Image from SQL Server to VB.Net Form

Regarding to previous post about how to store image use SQL command , here is the complete SQL commands and VB.Net source code and commands to display the image from SQL database to a VB.Net PictureBox on a Form.

Posting ini bisa disebut pelengkap dari postingan sebelumnya (http://ilmubiner.blogspot.com/2010/08/menyimpan-file-gambar-pada-database-sql.html) mengenai cara menyimpan image pada SQL server menggunakan perintah SQL. Nah sekarang adalah perintah SQL lengkap untuk menyimpan data image ke database dan source code VB.Net (2005) untuk menampilkan image dari database ke sebuah PictureBox.

SQL Server commands to create database, table, and insert commands to store images files :
create database ujicoba;

use ujicoba

CREATE TABLE pegawai (
 nip int,
 nama varchar(50) not null,
 foto varbinary(max) not null
)

INSERT INTO Pegawai (nip, nama, foto)
SELECT 10, 'Winona Ryder',
 BulkColumn from
 Openrowset( Bulk 'E:\winona.jpg', Single_Blob)
   as EmployeePicture

INSERT INTO Pegawai (nip, nama, foto)
SELECT 20, 'Jessica Alba',
 BulkColumn from
 Openrowset( Bulk 'E:\jess_alba.jpg', Single_Blob)
   as EmployeePicture

VB.Net source code to get image data stored in SQL Server and display to a Form (use PictureBox) :
Imports System.Data.SqlClient

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim con As New SqlConnection("Data Source=10.20.30.176;Initial Catalog=ujicoba; Integrated Security=True; Persist Security Info=FALSE;")
        con.Open()
        Dim cmd As New SqlCommand("select nip, nama, foto From pegawai", con)
        Dim dr As SqlDataReader = cmd.ExecuteReader()
        Dim dt As New DataTable
        dt.Load(dr)
        Dim row As DataRow = dt.Rows(0)
        txtNIP.Text = row("nip")
        txtNama.Text = row("nama")
        'Dim ms As New IO.MemoryStream(CType(row("foto"), Byte()))
        'Dim img As Image = Image.FromStream(New IO.MemoryStream(CType(row("foto"), Byte())))
        picBox.Image = Image.FromStream(New IO.MemoryStream(CType(row("foto"), Byte())))
    End Sub
End Class

1 komentar:

dhesky aris mengatakan...

ms, jk tidak keberatan bsa mnta tolong menampilkan gambar dari sql server pake php? udh ak cba, tp ndak bsa2.. trims