using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class cun_img : Form { public cun_img() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e)//-----------------------打開 { DialogResult dr = openFileDialog1.ShowDialog(); if (dr==DialogResult.OK) { FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);//打開讀取文件 讀到fs這個流裏面 Image img = System.Drawing.Bitmap.FromStream(fs);//fs從硬盤上讀取的圖片經過drawing.bitmap位圖繪製出來就是image類 pictureBox1.Image = img;//指定 } } private void button2_Click(object sender, EventArgs e)//---------------存入到數據庫 { DialogResult dr = openFileDialog1.ShowDialog(); if (dr==DialogResult.OK) { //文件流 FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs);//二進制讀取器 byte[] buffer = br.ReadBytes(int.Parse(fs.Length.ToString())); //鏈接數據庫 SqlConnection conn = new SqlConnection("server=.;database=tupian;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into imatable values(@buffer)"; cmd.Parameters.Add("@buffer", buffer); conn.Open(); cmd.ExecuteNonQuery(); cmd.Dispose(); conn.Close(); } } private void button3_Click(object sender, EventArgs e)//-----------------------從數據庫讀取 { SqlConnection conn = new SqlConnection("server=.;database=tupian;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select *from imatable"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); byte[] buffer = null; if (dr.Read()) { buffer = (byte[])dr["img"];//轉換爲byte數組型 } cmd.Dispose(); conn.Close(); //將二進制數據buffer顯示爲圖片 MemoryStream ms = new MemoryStream(buffer);//構建對象 Image img = System.Drawing.Image.FromStream(ms); pictureBox1.Image = img; } } }