using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 读取数据库中的图片
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 选择图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//初始化打开文件 对话框
OpenFileDialog ofdlgTest = new OpenFileDialog();
ofdlgTest.Filter = "*.jpg|*.png"; //文件过滤 筛选可以打开的文件
ofdlgTest.Multiselect = false; //设置不可以选择多个文件
//显示文件打开对话框
DialogResult result = ofdlgTest.ShowDialog();
//选择打开按钮的时候,将文件名显示到文本框中
if (result== DialogResult.OK) //判断是否打开文件
{
this.textBox1.Text = ofdlgTest.FileName;
pictureBox1.Image = Image.FromFile(ofdlgTest.FileName);
}
}
/// <summary>
/// 存入数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string constr = "Data Source=.;Initial Catalog=MyFirstDatabase;User Id=sa;PassWord=91811372c";
using(SqlConnection con=new SqlConnection(constr))
{
//sql语句 插入图片
string sql = "insert into ImageTest values(@UserImage)";
using(SqlCommand com=new SqlCommand(sql,con))
{
byte[] buffer; //将图片转换为字节数组 存入数据库 textBox1.Text 是文件的路径
using(FileStream stream = new FileStream(textBox1.Text, FileMode.OpenOrCreate, FileAccess.Read))
{
//通过文件路径 打开文件
buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length); //转换后 ,存入buffer中
}
//这个参数 其实 也没必要声明 不过习惯使用 带参数的sql语句了
SqlParameter pms = new SqlParameter("@UserImage", SqlDbType.Image) { Value = buffer };
com.Parameters.Add(pms);
con.Open();
string msg = com.ExecuteNonQuery()>0?"存入成功":"存入失败";
MessageBox.Show(msg);
}
}
}
/// <summary>
/// 从数据库中读取
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
string conStr = "Data Source=.;Initial Catalog=MyFirstDatabase;User Id=sa;PassWord=自己的密码";
using(SqlConnection con=new SqlConnection(conStr))
{
//sql语句
string sql = "select * from ImageTest";
using (SqlCommand com = new SqlCommand(sql, con))
{
con.Open();
using(SqlDataReader reader=com.ExecuteReader())
{
if (reader.HasRows)
{
//声明一字节数组 将数据库中的图片现存入字节数组中
byte[] imageByte;
//在这我是知道里面就一张图,所以这么写的,个人根据实际情况,可做修改
while(reader.Read())
{
//将图片转换为字节数组
imageByte = (byte[])reader["UserImage"];
//转换为文件流
MemoryStream stream = new MemoryStream(imageByte);
//再将文件流 转换为 图像
Bitmap bitmap = new Bitmap(stream);
pictureBox1.Image = bitmap;
}
}
}
}
}
}
}
}
|