将图片写入数据库和读取

来源:互联网 发布:软件实施工程师要求 编辑:程序博客网 时间:2024/06/05 02:53
 在C#中将图片写入数据库并读取出来.源码
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 将图片写入数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //用格式转换器直接将图片转换成二进制
            ImageConverter img = new ImageConverter();
            byte[] imgdate = (byte[])img.ConvertTo(this.pictureBox1.Image, typeof(byte[]));
            using (SqlConnection conn = new SqlConnection(Connstr))
            {
                SqlCommand comm = conn.CreateCommand();
                conn.Open();
                comm.CommandText = string.Format("insert into myimage(imgdate) values(@imgdate)");
                comm.Parameters.Add("@imgdate", SqlDbType.Image).Value = imgdate;
                comm.ExecuteNonQuery();//要用参数写入
                MessageBox.Show("Access");
            }
        }
        private string Connstr = @"server=./SQLEXPRESS;DATABASE = TEST;INTEGRATED SECURITY = TRUE";
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfd = new OpenFileDialog();
            if (openfd.ShowDialog() == DialogResult.OK)
            {
                this.pictureBox1.Image = Image.FromFile(openfd.FileName);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(Connstr))
            {
                SqlCommand comm = conn.CreateCommand();
                conn.Open();
                comm.CommandText = string.Format("select imgdate from myimage where imgid = {0}", 1);
                SqlDataReader read = comm.ExecuteReader();
                if (read.Read())
                {                    
                    byte[] imgdate = (byte[])read["imgdate"];
                    //用内存流实现
                    MemoryStream ms = new MemoryStream(imgdate);
                    this.pictureBox1.Image = Image.FromStream(ms);
                    //用格式转换器实现
                    //ImageConverter ic = new ImageConverter();
                    //this.pictureBox1.Image =(Image)ic.ConvertFrom(imgdate);                    
                }
                read.Close();
            }
        }
    }
}
原创粉丝点击