文档视界 最新最全的文档下载
当前位置:文档视界 › 将图片存入数据库

将图片存入数据库


C# 代码

一、将图片写入数据库中的方法:
SqlConnection conn=new SqlConnection("server=.;database=pubs;trusted_connection=Yes");
conn.Open();
SqlCommand scmd = null;
string Path = Application.StartupPath + "//Imgren"; //为获取文件的根目录
int j = 0;
FileStream fs=null;
for (int i = 1; i <= 13; i++) //利用循环添加一次添加图片
{
string sql = "insert into tb_Image values(@a,@b)"; //利用参数实现图片添加
scmd = new SqlCommand(sql, scon);

scmd.Parameters.Add("@a", SqlDbType.Int);
scmd.Parameters["@a"].Value = i; //记住该方法,将值存入参数内

byte[] bt = new byte[10240]; //初始化图片大小
//创建图片写入流
fs = new FileStream(Path + "//" + i + ".bmp", FileMode.OpenOrCreate, FileAccess.Read);
fs.Read(bt, 0, bt.Length); //读取图片的字节数
scmd.Parameters.Add("@b", SqlDbType.Image, (int)fs.Length);
scmd.Parameters["@b"].Value = bt; //将图片的字节数存入参数内
j = scmd.ExecuteNonQuery();
}
if (j > 0)
MessageBox.Show("将图片写入数据库成功!!!", "友好提示");
else
MessageBox.Show("将图片写入数据库失败!!!", "友好提示");
fs.Close(); //关闭释放流资源

二、从数据库中读取图片到picturebox中
根据编号显示图片哦:
SqlConnection conn=new SqlConnection("server=.;database=pubs;trusted_connection=Yes");
conn.Open();
SqlCommand scmd = null;
string sql = "select I_image from tb_image where I_id=" +int.Parse(textBox1.Text.Trim()) + "";
scmd = new SqlCommand(sql, scon);
SqlDataReader red = scmd.ExecuteReader();
if (red.Read())
{
//创建支持存储区的内存流
MemoryStream ms = new MemoryStream((byte[])red[0]);
Image img = Image.FromStream(ms, true); //该方法: FromStream()为验证图像的流
this.pictureBox1.Image = img;
}
red.Close(); //关闭资源

相关文档
相关文档 最新文档