將圖片寫入數據庫和讀取

 在C#中將圖片寫入數據庫並讀取出來.源碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace 將圖片寫入數據庫
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //用格式轉換器直接將圖片轉換成二進制
            ImageConverter img = new ImageConverter();
            byte[] imgdate = (byte[])img.ConvertTo(this.pictureBox1.Image, typeof(byte[]));
            using (SqlConnection conn = new SqlConnection(Connstr))
            {
                SqlCommand comm = conn.CreateCommand();
                conn.Open();
                comm.CommandText = string.Format("insert into myimage(imgdate) values(@imgdate)");
                comm.Parameters.Add("@imgdate", SqlDbType.Image).Value = imgdate;
                comm.ExecuteNonQuery();//要用參數寫入
                MessageBox.Show("Access");
            }
        }
        private string Connstr = @"server=./SQLEXPRESS;DATABASE = TEST;INTEGRATED SECURITY = TRUE";
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfd = new OpenFileDialog();
            if (openfd.ShowDialog() == DialogResult.OK)
            {
                this.pictureBox1.Image = Image.FromFile(openfd.FileName);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(Connstr))
            {
                SqlCommand comm = conn.CreateCommand();
                conn.Open();
                comm.CommandText = string.Format("select imgdate from myimage where imgid = {0}", 1);
                SqlDataReader read = comm.ExecuteReader();
                if (read.Read())
                {                    
                    byte[] imgdate = (byte[])read["imgdate"];
                    //用內存流實現
                    MemoryStream ms = new MemoryStream(imgdate);
                    this.pictureBox1.Image = Image.FromStream(ms);
                    //用格式轉換器實現
                    //ImageConverter ic = new ImageConverter();
                    //this.pictureBox1.Image =(Image)ic.ConvertFrom(imgdate);                    
                }
                read.Close();
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章