将图片写入数据库和读取

 在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();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值