winform中把照片存储到数据库中
winform中 把图片存储到数据库中! 第一次写这样的例子!
有不懂的可以去我hi.baidu.com/hnpylwp 留言我会回复大家的!
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 Save_img_data
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn=null;
string conntext = @"server=PC-200903031559\HNPYLWP;database=images;integrated security=true";
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(conntext);
this.Bind();
}
private void btnSan_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter = "矢量图(*.jpg;*.jpeg)|*.jpg;*.jpeg|位图(*.bmp)|*.bmp|gif格式|*.gif";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = this.openFileDialog1.FileName;
this.pictureBox1.Image = Image.FromFile(this.openFileDialog1.FileName);
}
}
public void Bind()
{
string sqltext = "select imgid,imgname,imglength from img";
SqlDataAdapter da = new SqlDataAdapter(sqltext,conn);
DataSet ds = new DataSet();
da.Fill(ds, "images");
this.dataGridView2.DataSource = ds.Tables["images"];
}
private void btnSave_Click(object sender, EventArgs e)
{
string Filename = Path.GetFileName(this.openFileDialog1.FileName);
MemoryStream ms = new MemoryStream();
this.pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] buffer = ms.ToArray();
int FileLength =(int)buffer.Length;
string sqltext = "insert into img(imgname,imglength,imgdata) values('" + Filename + "',@length,@data);";
SqlCommand cmd = new SqlCommand(sqltext, conn);
cmd.Parameters.Add("@length", SqlDbType.BigInt);
cmd.Parameters["@length"].Value = buffer.Length;
cmd.Parameters.Add("@data", SqlDbType.Image, buffer.Length);
cmd.Parameters["@data"].Value = buffer;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Save OK");
this.Bind();
}
private void dataGridView2_RowEnter(object sender, DataGridViewCellEventArgs e)
{
this.Showimg((int)this.dataGridView2.Rows[e.RowIndex].Cells[0].Value);
}
public void Showimg(int imgid)
{
string sqltext = "select imgdata from img where imgid=" + imgid;
SqlCommand cmd = new SqlCommand(sqltext, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
byte[] buffer = (byte[])dr["imgdata"];
conn.Close();
MemoryStream ms = new MemoryStream(buffer);
this.pictureBox1.Image = Image.FromStream(ms);
}
}
}

浙公网安备 33010602011771号