Cách lưu hình ảnh vào csdl Sql Server

Đầu tiên, các bạn tạo csdl có 1 table như hình dưới:


Tiếp theo, các bạn tạo 1 form có giao diện như hình dưới (Ở giữa là 1 picture box và bên cạnh là các nút điều khiển.



Tiếp theo, các bạn tạo 1 class có tên AccessData.cs. Nội dung class đó như sau:

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Data.SqlClient;

namespace ImageInSQL
{
class AccessData
{
public SqlConnection conn;

public string connectionString =
"Data Source=.\\SQLEXPRESS;AttachDbFilename='E:\\My Code\\C#\\ImageInSQL\\ImageInSQL\\ImageData.mdf';Integrated Security=True;User Instance=True";
public AccessData()
{
conn = new SqlConnection(connectionString);
}
public void StorePicture(string filename)
{
byte[] imageData = null;
// Read the file into a byte array
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
imageData = new Byte[fs.Length];
fs.Read(imageData, 0, (int) fs.Length);
}
string shortFileName = filename.Split('\\').Last();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("InsertImage", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@filename", shortFileName);
cmd.Parameters["@filename"].Direction = ParameterDirection.Input;
cmd.Parameters.Add("@Image",SqlDbType.Image);
cmd.Parameters["@Image"].Direction = ParameterDirection.Input;
// Store the byte array within the image field
cmd.Parameters["@Image"].Value = imageData;
conn.Open();
cmd.ExecuteNonQuery();
}
}

public byte[] RetrieveImage(int id)
{
byte[] imageData = null;
conn.Open();
SqlCommand cmd = new SqlCommand("select Image from tbl_Image where ID="+id+"",conn);
// Assume previously established command and connection
// The command SELECTs the IMAGE column from the table

using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
reader.Read();
// Get size of image data – pass null as the byte array parameter
long bytesize = reader.GetBytes(0, 0, null, 0, 0);
// Allocate byte array to hold image data
imageData = new byte[bytesize];
long bytesread = 0;
int curpos = 0;
int chunkSize = 1;
while (bytesread < bytesize)
{
// chunkSize is an arbitrary application defined value
bytesread += reader.GetBytes(0, curpos, imageData, curpos, chunkSize);
curpos += chunkSize;
}
}
conn.Close();
// byte array ‘imageData’ now contains BLOB from database
return imageData;
}
public int NumberImageInDB()
{
conn.Open();
SqlCommand cmd=new SqlCommand("select Max(ID) from tbl_Image",conn);
int kq = int.Parse(cmd.ExecuteScalar().ToString());
cmd.Dispose();
conn.Close();
return kq;
}
public string FileNameOfImage(int id)
{
conn.Open();
SqlCommand cmd = new SqlCommand("select FileName from tbl_Image where ID="+id+"", conn);
string kq = cmd.ExecuteScalar().ToString();
cmd.Dispose();
conn.Close();
return kq;
}
}
}

Các bạn cần chỉnh lại connectionString cho đúng với máy mình.
vào phần code của form khai báo đối tượng AccessData và 2 biến private để lưu tên file và chỉ số ảnh

AccessData ac=new AccessData();
private string filename;
private int i=1;

Tiếp theo sẽ là code cho từng nút:
Nút select picture

OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter ="All File (*.*)|*.*|JPG Files(*.JPG)|*.JPG | GIF Files(*.GIF)|*.GIF";
if (dlg.ShowDialog(this) == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
filename = dlg.FileName;
blFileName.Text = filename.Split('\\').Last();
}

Nút save to DB

try
{
ac.StorePicture(filename);
MessageBox.Show("Successful!", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Nút picture first

byte[] img = ac.RetrieveImage(1);
MemoryStream str = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(str);
i = 1;
button5.Enabled = false;
button3.Enabled = true;
blFileName.Text = ac.FileNameOfImage(1);

Nút next

button5.Enabled = true;
if (i < ac.NumberImageInDB()) i++;
else button3.Enabled = false;
byte[] img = ac.RetrieveImage(i);
MemoryStream str = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(str);
blFileName.Text = ac.FileNameOfImage(i);

Nút preview

button3.Enabled = true;
if (i >1) i--;
else button5.Enabled = false;
byte[] img = ac.RetrieveImage(i);
MemoryStream str = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(str);
blFileName.Text = ac.FileNameOfImage(i);

Nút picture last

byte[] img = ac.RetrieveImage(ac.NumberImageInDB());
MemoryStream str = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(str);
i = ac.NumberImageInDB();
button3.Enabled = false;
button5.Enabled = true;
blFileName.Text = ac.FileNameOfImage(ac.NumberImageInDB());

Vậy là xong, các bạn có thể test thử và xem kết quả.
Download code full

Chúc các bạn thành công!

6 nhận xét:

Admin nói...

sau khi tạo xong csdl, các bạn thêm 1 storeprocedure như sau:
CREATE PROCEDURE InsertImage
@filename nvarchar(250),
@Image image
AS
insert into tbl_Image values(@filename, @Image)

Sorry mình thiếu phần đó, ko edit lại được, mong các bạn thông cảm

ndqvinh nói...

Cám ơn bạn nhiều nhiều

ndqvinh nói...

bạn ơi chỗ store procedure chỉ insert có 2 cột nhưng trong cơ sở dữ liệu thì tới 3 cột, mình đã tạo nhưng sqlserver báo lỗi.

caovietthuong nói...

insert vào cột nào thì liệt kê nó ra, trước từ khóa values ấy !
Ví dụ :
insert into Table1(Colum1,Colum2) values (val1,val2)

Bi K nói...

CREATE PROCEDURE
bạn có thể nói rõ phần này chút không , mình ko thêm vào được .thanks

hung nói...

MemoryStream str = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(str)

đoạn mã này mình làm nó báo lỗi "Parameter is not valid." là sao nhỉ?