Thứ Hai, 3 tháng 1, 2011

Đầ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!

Related Posts:

  • Xóa file vào xọt rác bằng C#Chỉ với 3 bước đơn giản sau, bạn có thể code cho ứng dụng của mình chức năng xóa file vào xọt rác của windows. 1. Add reference Microsoft.VisualBasic2. using Microsoft.VisualBasic.FileIO;3. dùng hàm FileSystem.DeleteFile với … Read More
  • Bắt sự kiện ấn phím enterTrong nhiều trường hợp, chúng ta cần nhận biết có ấn phím enter hay không để xử lý một sự kiện tự động, không cần phải sử dụng chuột. Chúng ta sử dụng đoạn code sau: protected override bool ProcessDialogKey(Keys keyData){ if… Read More
  • Thao tác với REGISTRY trong C#Registry là một cơ sở dữ liệu dùng để lưu trữ thông tin về những sự thay đổi, những lựa chọn, những thiết lập từ người sử dụng Windows. Registry bao gồm tất cả các thông tin về phần cứng, phần mềm, người sử dụng. Registry luô… Read More
  • Xây dựng Windows Service với C# – Phần 1Bài viết này sẽ hướng dẫn các bạn viết một trình ứng dụng với mục tiêu âm thầm theo dõi giám sát một thư mục nào đó trên máy tính. Do trình ứng dụng thuộc loại Windows Service nên sau khi viết xong các bạn có thể cài đặt và v… Read More
  • String Format trong C#Trong khi lập trình, chúng ta thường gặp phải rất nhiều trường hợp cần định dạng lại một chuỗi như chuỗi số, chuỗi ngày tháng sao cho đúng yêu cầu. Ví dụ: định dạng ngày tháng: MM/dd/yyyy ta muốn chuyển sang dd/MM/yyyy cho th… Read More

0 nhận xét:

Đăng nhận xét

Categories

Sample Text

Được tạo bởi Blogger.

Must Read

Biểu mẫu liên hệ

Tên

Email *

Thông báo *

Popular Posts

Video

Popular Posts

Our Facebook Page