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))
{
string
sql =
"insert into ImageTest values(@UserImage)"
;
using
(SqlCommand com=
new
SqlCommand(sql,con))
{
byte
[] buffer;
using
(FileStream stream =
new
FileStream(textBox1.Text, FileMode.OpenOrCreate, FileAccess.Read))
{
buffer =
new
byte
[stream.Length];
stream.Read(buffer, 0, buffer.Length);
}
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))
{
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;
}
}
}
}
}
}
}
}