kết quả từ 1 tới 2 trên 2

Ðề tài: Cách lưu hình ảnh vào database trong C Sharp

  1. #1
    Join Date
    Aug 2009
    Bài gởi
    71
    Thanks
    0
    Thanked 6 Times in 6 Posts

    Học tập suôt đời! Cách lưu hình ảnh vào database trong C Sharp

    Database là Microsoft SQL Server
    1. Tạo database có tên: TestImageDB với 1 bảng có tên tblImages và có cấu trúc như hình sau:


    2. Tạo stored project có tên InsertImage với sql script như sau:
    CREATE PROCEDURE InsertImage
    @filename nvarchar(250),
    @blobdata image
    AS
    insert into tblImages values(
    @filename, @blobdata
    )
    3. Tạo Windows Form Application Project có tên AnotherWay.
    4. Tạo lớp ConnectDB.cs có nội dung như sau:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Data;
    using System.Data.SqlClient;
    namespace AnotherWay
    {
    class ConnectDB
    {
    private SqlConnection conn;
    private string connectionString = "Server=.;UID=sa;PWD=;Initial Catalog=TestImageDB";
    public ConnectDB()
    {
    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);
    }
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
    SqlCommand cmd = new SqlCommand("InsertImage", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@filename", filename);
    cmd.Parameters["@filename"].Direction = ParameterDirection.Input;
    cmd.Parameters.Add("@blobdata", SqlDbType.Image);
    cmd.Parameters["@blobdata"].Direction = ParameterDirection.Input;
    // Store the byte array within the image field
    cmd.Parameters["@blobdata"].Value = imageData;
    conn.Open();
    cmd.ExecuteNonQuery();
    }
    }
    public byte[] RetrieveImage()
    {
    byte[] imageData = null;
    conn.Open();
    SqlCommand cmd = new SqlCommand("select blobdata from tblImages", 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;
    }
    }
    }
    5. Thiết kế Form như hình


    6. Code cho Form:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Windows.Forms;
    namespace AnotherWay
    {
    public partial class Form1 : Form
    {
    private ConnectDB conDB;
    public Form1()
    {
    InitializeComponent();
    conDB = new ConnectDB();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Filter = "JPG Files(*.JPG)|*.JPG|GIF Files(*.GIF)|*.GIF";
    if (dlg.ShowDialog(this) == DialogResult.OK)
    {
    conDB.StorePicture(dlg.FileName);
    }
    }
    private void button2_Click(object sender, EventArgs e)
    {
    byte[] img = conDB.RetrieveImage();
    MemoryStream str = new MemoryStream(img);
    pictureBox1.Image = Image.FromStream(str);
    }
    }
    }
    7. Thực thi
    Trước hết nhấn nút Lưu, sau đó muốn xem lại mẫu tin đã lưu, nhấn nút load.


    Chúc thành công!
    Theo vovanhai
    Nguồn: Cách lưu hình ảnh vào database trong C sharp (P2)
    __________________________________________________ ______________________________
    Nghề kiểm thử phần mềm bạn đã biết chưa? Nguồn: http://diendankienthuc.net.

  2. The Following User Says Thank You to hoangphuong2003 For This Useful Post:


  3. #2
    Join Date
    Jul 2010
    Bài gởi
    6
    Thanks
    2
    Thanked 2 Times in 2 Posts

    Học tập suôt đời!

    Bài tut của thầy Hải khá ấn tượng
    cảm ơn bạn nhiều khi đã sưu tầm cho anh em

    thân Nguồn: http://diendankienthuc.net.
    Vận tải: http://vantaingocdiep.divivu.com
    Ván ép: http://vanepphuongly.divivu.com :byebye:

Chủ đề giống nhau

  1. Hàm lấy kí tự trong chuỗi trong Visual Studio 2005
    By baohoa2886 in forum Thủ thuật tin học
    Trả lời: 0
    Bài mới gởi: 02-18-2011, 05:18 PM
  2. Truy cập các giá trị của Server trong C sharp
    By hoangphuong2003 in forum Web Development
    Trả lời: 0
    Bài mới gởi: 12-31-2010, 04:36 PM
  3. Cách chèn hình ảnh trực tiếp vào database trong C Sharp (P1)
    By hoangphuong2003 in forum Tri thức công nghệ
    Trả lời: 0
    Bài mới gởi: 12-10-2010, 06:23 PM
  4. Sharp trình làng "hạt đậu gỗ"
    By Butchi in forum Tri thức công nghệ
    Trả lời: 1
    Bài mới gởi: 11-17-2010, 11:34 AM
  5. Hội thảo công nghệ: Database and Developer
    By minku in forum Tri thức công nghệ
    Trả lời: 0
    Bài mới gởi: 09-29-2010, 10:38 PM

Bookmarks

Quuyền Hạn Của Bạn

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •