C# 存取数据库中的图像

来源:互联网 发布:易语言播放器源码 编辑:程序博客网 时间:2024/05/27 09:46

 一、数据库中的图像存取方法
1. 读取image类型的数据
读取image类型数据的方法可分为以下几步:
1) 先使用无符号字节数组存放数据库对应的数据集中表的image类型字段的值。例如:
byte[] bytes= (byte[]) image类型字段值
2) 使用MemoryStream类,该类创建支持存储区为内存的流。即MemoryStream类创建的流以内存而不是磁盘或网络连接作为支持存储区。其构造函数为:
public MemoryStream(byte[] buffer);
3) 使用Bitmap类,该类封装了GDI 位图,此位图由图像图像及其属性的像素数据组成。Bitmap对象是用于处理由像素数据定义的图像的对象。其构造函数为:
public Bitmap(Stream stream);
4) 在窗体中利用PictureBox控件对象显示图像。
2. 保存image类型的数据
保存image类型数据的方法也分为以下几步:
1) 使用Stream类,首先从图像文档中获取流对象,再利用该类的Read方法从图像文档中读取二进制数据存入字节数组中。Read方法为:
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
2) 将字节数组中的值存入数据库对应的数据集中表的image字段。格式为:
image类型字段= bytes;
3) 更新数据库,就能够完成保存图像数据的功能。
二、 数据库中的图像存取示例
下面通过一个例子说明如何存取SQL Server数据库中的图像。
(1) 创建一个Windows应用程式,设计窗体界面如图所示。

⑵ 添加名称空间引用
using System.Data;
using System.Data.SqlClient;
using System.IO;
⑶ 添加字段声明
private string connString="server=localhost; integrated security=sspi; database=pubs";
SqlConnection conn;
SqlDataAdapter adapter;
DataSet dataset;
⑷ 在构造函数中添加代码
string sqlstr="select * from pub_info";
conn=new SqlConnection(connString);
adapter=new SqlDataAdapter(sqlstr,conn);
SqlCommandBuilder builder=new SqlCommandBuilder(adapter);
adapter.UpdateCommand=builder.GetUpdateCommand();
dataset=new DataSet();
adapter.Fill(dataset,"pub_info");
//将text1Box1的Text属性绑定到dataset中的pub_info表的pr_info字段
this.textBox1.DataBindings.Add(new Binding("Text",dataset,"pub_info.pr_info"));
for(int i=0;i<dataset.Tables[0].Rows.Count;i )
{
this.listBox1.Items.Add(dataset.Tables[0].Rows[i][0]);
}
⑸ 添加调用的方法
private void ShowImage()
{
byte[] bytes= (byte[])dataset.Tables[0].Rows[this.listBox1.SelectedIndex][1];
MemoryStream memStream=new MemoryStream(bytes);
try
{
Bitmap myImage = new Bitmap(memStream);
this.pictureBox1.Image= myImage;
}
catch
{
this.pictureBox1.Image=null;
}
}
⑹ 添加“更换图片”的Click事件代码
private void buttonUpdateImage_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1=new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName.Trim()!="")
{
Stream myStream = openFileDialog1.OpenFile();
int length=(int)myStream.Length;
byte[] bytes=new byte[length];
myStream.Read(bytes,0,length);
myStream.Close();
dataset.Tables[0].Rows[this.listBox1.SelectedIndex][1] =bytes;
ShowImage();
}
}
⑺ 添加“移除图片”的Click事件代码
private void buttonMoveImage_Click(object sender, System.EventArgs e)
{
byte[] bytes= System.Text.Encoding.Unicode.GetBytes("");
dataset.Tables[0].Rows[this.listBox1.SelectedIndex][1]=
bytes;
ShowImage();
}
⑻ 添加“保存更改”的Click事件代码
private void buttonSave_Click(object sender, System.EventArgs e)
{
adapter.Update(dataset,"pub_info");
MessageBox.Show("保存成功");
}
⑼ 添加listBox1的SelectedIndexChanged事件代码
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
ShowImage();
this.BindingContext[dataset,"pub_info"].Position
=this.listBox1.SelectedIndex;
}
(10) 运行。
能够更换图片,也能够直接修改textBox1中的内容。

原创粉丝点击