在数据库中存取图片文件一般有2中方式,一存储字节流,二存储图片存放路径,这里分别介绍一下两种方式。
-
数据库示例表
create databse mydb
go
use mydb
--示例表1 用户表(存储图片字节流)
create table users(id int identity(1,1) primary key,username varchar(30),photo image)
--示例表2 人员表(存储图片路径)
create table persons(id int identity(1,1) primary key,username varchar(30),photo varchar(200))
1.存取字节流方式存取图片
-
保存图片到数据库
保存图片到数据库image(sqlserver数据库中的图片字段类型)类型,其实和其他数据库的blob 类型差不多,都是存储长字节字段的,既然是字节存储方式,那么就首先需要把要存储的内容转换为字节数组,然后在存储。
-
Code
private void SaveData2() {
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "照片(*.png,*.jpg,*.jpeg,*.bmp)|*.png;*.jpg;*.jpeg;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
pictureBox1.Load(openFileDialog.FileName);
if ((sm = openFileDialog.OpenFile()) != null) {
picByte=new byte[sm.Length];
//将图片内存流读取到字节数组中
sm.Position = 0;
sm.Read(picByte, 0, Convert.ToInt32(sm.Length));
sm.Dispose();
using (SqlCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into users(username,photo) values(@username,@photo)";
cmd.Parameters.Add("@username", SqlDbType.VarChar);
cmd.Parameters.Add("@photo", SqlDbType.Image);
cmd.Parameters["@username"].Value = textBox1.Text;
cmd.Parameters["@photo"].Value = picByte; //字节流保存到对应的字段中
cmd.ExecuteNonQuery();
}
}
}
}
-
读取并显示图片
从数据库中读取到的图片数据是字符串形式,需要转换成字节数组,然后再读入到流中,最后可以通过图片控件PictureBox 加载图片流。如果在DataGridView中,会自动显示图片数据,这里需要把(DataGridView.Columns["photo"] as DataGridViewImageColumn).ImageLayout=(DataGridViewImageCellLayout)ImageLayout.Stretch
把图片列设置成自动扩展。
-
Code
private void button2_Click(object sender, EventArgs e)
{
using (SqlCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "select * from users";
SqlDataAdapter sda=new SqlDataAdapter(cmd);
DataSet ds=new DataSet();
sda.Fill(ds);
uiDataGridView1.DataSource = ds.Tables[0];
(uiDataGridView1.Columns["photo"] as DataGridViewImageColumn).ImageLayout = (DataGridViewImageCellLayout)ImageLayout.Stretch;
}
}
//或者在列数据加载时设置
private void uiDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//检查当前单元格是否为图像列
if (uiDataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.Value != null)
{
//加载图像到临时的Image对象
(uiDataGridView1.Columns[e.ColumnIndex] as DataGridViewImageColumn).ImageLayout = (DataGridViewImageCellLayout)ImageLayout.Stretch;
}
}
2.存取路径方式存取图片
存取路径方式比较简单,就是直接把路径以字符串形式存储在数据库字段中,读取时进行转换。
写入
-
Code
private void uiButton2_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null) {
Bitmap bmp = new Bitmap(pictureBox1.Image);
path= $"\\photo\\{textBox1.Text}.png";
bmp.Save(DirEx.CurrentDir() + @path, ImageFormat.Png);
}
using(SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = "insert into persons(name,photo) values(@name,@photo)";
cmd.Parameters.Add("@name", SqlDbType.VarChar);
cmd.Parameters.Add("@photo",SqlDbType.VarChar);
cmd.Parameters["@name"].Value = textBox1.Text;
cmd.Parameters["@photo"].Value = path;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
GetData1(); //调用读取方法,加载数据
}
读取
-
Code
private void GetData1() {
uiDataGridView2.AllowUserToAddRows = false;//自动增加空行
using (SqlCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "select * from persons";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
uiDataGridView2.DataSource = ds.Tables[0];
}
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.HeaderText = "照片";
imageColumn.Name = "photoImage";
imageColumn.Width = 150;
imageColumn.ImageLayout = (DataGridViewImageCellLayout)ImageLayout.Stretch;
uiDataGridView2.Columns.Add(imageColumn);
uiDataGridView2.Refresh();
foreach (DataGridViewRow row in uiDataGridView2.Rows)
{
string imagePath = row.Cells["photo"].Value.ToString();
if (!imagePath.Contains(':'))
{
imagePath = DirEx.CurrentDir() + imagePath;
}
Image image = Image.FromFile(imagePath);
row.Cells["photoImage"].Value = image;
}
}
标签:Parameters,photo,数据库,cmd,SqlServer,ImageLayout,new,存取,图片
From: https://www.cnblogs.com/sundh1981/p/18312735