图片存入数据库需要把图片转成二进制才能存入,怎么把图片转成二进制,这就是关键。
首先,在sql数据库建一个表image,只有一个字段im,数据类型image。
建好之后,打开visual studio,建一个windows窗体应用程序
下面是效果图:
代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; namespace TestForm1 { public partial class FormImageInSql : Form { public FormImageInSql() { InitializeComponent(); } /// <summary> /// 存入数据库 /// </summary> private void btn_before_Click(object sender, EventArgs e) { string filePath = @"....Imagesqiaoba.jpg";//WinForm窗体项目起始在debug文件夹下,写路径的时候注意了 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); SqlConnection con = DBHelper.getConnection(); string cmd_str = "insert into Image values(@buffer)"; SqlCommand cmd = new SqlCommand(cmd_str, con); SqlParameter para = new SqlParameter("@buffer", SqlDbType.Image); para.Value = buffer; cmd.Parameters.Add(para); con.Open(); cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("存入成功!"); } /// <summary> /// 从数据库中读出 /// </summary> private void btn_after_Click(object sender, EventArgs e) { string con_str = "select top 1 im from Image "; SqlConnection con = DBHelper.getConnection(); SqlCommand cmd = new SqlCommand(con_str, con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); MemoryStream ms = new MemoryStream((byte[])dr["im"]); Image image = Image.FromStream(ms, true); dr.Close(); con.Close(); pb_after.SizeMode = PictureBoxSizeMode.StretchImage; pb_after.Image = image; } } }