昨天看老师关于数据库二进制数据存储视频之后,自己动手了写了一个简版图片存储。分享交流一下!网上关于图片存储写法过于繁杂。我简化了一下。代码如下!- 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.Data.SqlClient;
- using System.IO;
- namespace 图片存取
- {
- public partial class Form1 : Form
- {
-
- public Form1()
- {
- InitializeComponent();
- }
- SqlConnection conn;
- SqlDataReader myreader;
- byte[] photo = null;
- #region //定义一个静态变量区
- public const string conString = "server=.;database=mis4;uid=sa;pwd=";
- #endregion
- private void button1_Click(object sender, EventArgs e)
- {
- SqlCommand cmd1 = new SqlCommand("insert image values(@image_id,@image_tupian)", conn);
- cmd1.Parameters.Add("@image_id", SqlDbType.Int, 4).Value = textBox1.Text;
- cmd1.Parameters.Add("@image_tupian", SqlDbType.Image, photo.Length).Value = photo;
- conn.Open();
- cmd1.ExecuteNonQuery();
- conn.Close();
-
-
- }
- private void button2_Click(object sender, EventArgs e)
- {
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.AddExtension = true;
- ofd.Title = "图片选择过滤器";
- ofd.Filter = "file(*.jpg)|*.jpg|file(*.bmp)|*.bmp";
- if(ofd.ShowDialog()==DialogResult.OK)
- {
-
- pictureBox1.Image = Image.FromFile(ofd.FileName);
- FileStream fs = new FileStream(ofd.FileName,FileMode.Open,FileAccess.Read);
- BinaryReader br = new BinaryReader(fs);
- photo = br.ReadBytes((int)fs.Length);
- br.Close();
- fs.Close();
- }
- }
- private void button3_Click(object sender, EventArgs e)
- {
- pictureBox1.Image = null;
- SqlCommand cmd2 = new SqlCommand("select image_tupian from image where image_id='" + textBox1.Text + "'",conn);
- <font color="#ff0000"> //conn.Open();
- //myreader = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
- //if (myreader.Read())
- //{
- // photo =(byte[])myreader.GetValue(0);//这是第一种图片读取方法,
- //}
- //MemoryStream ms = new MemoryStream(photo);
- //pictureBox1.Image = Image.FromStream(ms);
- //ms.Close();
- //myreader.Close();</font>
- <font color="#0000ff"> conn.Open();
- photo = (byte[])cmd2.ExecuteScalar();
- MemoryStream ms = new MemoryStream(photo);//这是第二种图片读取方法,简单了很多
- if (ms.Length > 0)
- {
- pictureBox1.Image = Image.FromStream(ms);
- }
- else
- pictureBox1.Image = null;
- conn.Close();
- }</font>
- private void Form1_Load(object sender, EventArgs e)
- {
-
- conn = new SqlConnection(global.conString);
- SqlDataAdapter sda = new SqlDataAdapter("Select * from image",conn);
- DataSet ds = new DataSet();
- sda.Fill(ds,"image");
- dataGridView1.DataSource=ds.Tables["image"].DefaultView;
-
- }
- private void button4_Click(object sender, EventArgs e)
- {
- Form2 f2 = new Form2();
- f2.ShowDialog();
- }
- }
- }
复制代码 |