您的位置:首页 > 服装鞋帽 > 衬衫 > 【引用】c#从数据库中保存/获取图片

【引用】c#从数据库中保存/获取图片

luyued 发布于 2011-03-04 06:48   浏览 N 次  

//读取图片并显示在 PictureBox

private void Read_Image(OpenFileDialog open, PictureBox myImage)
{
open.Filter = "*.jpg|*.jpg|*.bmp|*.bmp"; //过滤图片类型
if (open.ShowDialog() == DialogResult.OK) //打开选择对话框
{
try
{
myImage.Image = System.Drawing.Image.FromFile(open.FileName); //将图片文件存入到PictureBox控件中
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

//上传图片保存到数据库中

private void save_Image(OpenFileDialog Iopen)
{
try
{

string img = Iopen.FileName.ToString(); //获取上传图片路径名称
FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] imgBty = br.ReadBytes((int)fs.Length); //将流读入到字节数组中

string sql = "insert into test_pic(pic) values(@image)"; //保存图片需参数形式.

SqlConnection conn = new SqlConnection(); // 创建链接数据库
conn.ConnectionString = "server=localhost;database=NPI;uid=NPI;pwd=npi123";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add("@image", SqlDbType.Binary); //添加参数 参数类型二进制
cmd.Parameters["@image"].Value = imgBty;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
MessageBox.Show("图片上传成功!");
cmd.Dispose();
conn.Close();
combind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}

----------------------------------------------------------------------------------------------------------------------------------------------------------
//从数据库中获取图片

private void Get_Image(int id, PictureBox pic)
{
try
{
byte[] imageByte = null;

string sql = "select * from test_pic where id=" + id;

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=localhost;database=NPI;uid=NPI;pwd=npi123";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = conn;

SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
imageByte = (byte[])dr.GetValue(1);
}

dr.Close();
conn.Close();
MemoryStream ms = new MemoryStream(imageByte,true);
Bitmap bmpt = new Bitmap(ms);
pic.Image = bmpt;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}


}

广告赞助商