dataGridView某一列显示图片,t图片从数据库读取
程序员文章站
2022-07-15 13:45:52
...
在数据库中存照片的方式:
winform使用dataGridView显示图片;
把图片转换成byte[]二进制流,然后在把二进制转换成字符串
FileStream fs = new FileStream("图片路径", FileMode.Open);
byte[] imageBytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//图片转换成二进制流
string str = Convert.ToBase64String(imageBytes);//二进制转成base64字符串
然后把字符串存入数据表图片列中。
insert into UserInfo(Image) values('" + str + "')
取照片的时候,把字符串转换成二进制,在转成图片
MemoryStream ms = new MemoryStream(str);
Image img = System.Drawing.Image.FromStream(ms);
下面是小demo的代码:
使用的是SqlLite数据库,数据库都一样,数据表信息如下:
代码:
//选择图片
private void btnImg_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
textBox3.Text = open.FileName;
}
//信息插入数据库
private void btnInsert_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(textBox3.Text.Trim(), FileMode.Open);
byte[] imageBytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//图片转换成二进制流
string str = Convert.ToBase64String(imageBytes);//二进制转换成字符串
string sql2 = "insert into UserInfo(Name,Age,Image) values('" + textBox1.Text.Trim() + "','" + textBox2.Text.Trim() + "','" + str + "')";
int a = db.ExecuteNonQuery(sql2, null);
GetData();
}
//展示数据
private void GetData()
{
string sql = "select * from UserInfo";
DataTable dt = db.ExecuteDataTable(sql, null);
dataGridView1.ClearSelection();//取消选择第一行
dataGridView1.DataSource = dt;
}
//dataGridView事件里面的,头像列需要设置为图片格式
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Image"))
{
byte[] str = Convert.FromBase64String(e.Value.ToString());
e.Value = GetImage(str);
}
}
public Image GetImage(byte[] str)
{
MemoryStream ms = new MemoryStream(str);
Image img = System.Drawing.Image.FromStream(ms);
return img;
}