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; } } }