我这有代码,读写都有,你自己看吧:- 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 //定义一个静态变量区
-
- #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);
- //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();
- 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();
- }
- 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();
- }
- }
- }
复制代码 |