C#中怎么把picturebox中图片存到sql2005数据库,并把图片读取出来。给我代码举例,谢谢个位了~!
2个回答
展开全部
将图片转换为二进制存入数据库
Stream aa;
OpenFileDialog opg = new OpenFileDialog();
if (opg.ShowDialog() == DialogResult.OK)
{
pictureBox2.Load(opg.FileName);//获取要上传的图片
aa= opg.OpenFile();
}
string con = "data source=.;uid=sa;pwd=;database=master";
SqlConnection conn = new SqlConnection(con);
byte[] bytes = new byte[aa.Length];
aa.Read(bytes, 0, (int)aa.Length);
conn.Open();
string sql1 = string.Format("insert into 数据库表格 values('{0}',@phone)", 用户名);
SqlCommand cmd1 = new SqlCommand(sql1, conn);
cmd1.Parameters.Add("@phone", SqlDbType.Image).Value = bytes;
cmd1.ExecuteNonQuery();
conn.Close();
MessageBox.Show( "用户名的图片已上传");
从数据库得到二进制图片,转化为pictrue:
string sql = "select 图片 from 数据库表格 where name=用户名";
SqlConnection conn = new SqlConnection("data source=.;uid=sa;pwd=****;database=master");
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
byte[] bs = (byte[])r["图片"];
MemoryStream ms = new MemoryStream(bs, true);
ms.Write(bs, 0, bs.Length);
pictureBox1.Image = new Bitmap(ms, true);
ms.Dispose();
conn.close();
这里要添加 system.drawiing; system.data.sqlclient;system.sqlclient.sqltype;空间,你自己加入、
Stream aa;
OpenFileDialog opg = new OpenFileDialog();
if (opg.ShowDialog() == DialogResult.OK)
{
pictureBox2.Load(opg.FileName);//获取要上传的图片
aa= opg.OpenFile();
}
string con = "data source=.;uid=sa;pwd=;database=master";
SqlConnection conn = new SqlConnection(con);
byte[] bytes = new byte[aa.Length];
aa.Read(bytes, 0, (int)aa.Length);
conn.Open();
string sql1 = string.Format("insert into 数据库表格 values('{0}',@phone)", 用户名);
SqlCommand cmd1 = new SqlCommand(sql1, conn);
cmd1.Parameters.Add("@phone", SqlDbType.Image).Value = bytes;
cmd1.ExecuteNonQuery();
conn.Close();
MessageBox.Show( "用户名的图片已上传");
从数据库得到二进制图片,转化为pictrue:
string sql = "select 图片 from 数据库表格 where name=用户名";
SqlConnection conn = new SqlConnection("data source=.;uid=sa;pwd=****;database=master");
SqlCommand cmd = new SqlCommand(sql,conn);
conn.Open();
byte[] bs = (byte[])r["图片"];
MemoryStream ms = new MemoryStream(bs, true);
ms.Write(bs, 0, bs.Length);
pictureBox1.Image = new Bitmap(ms, true);
ms.Dispose();
conn.close();
这里要添加 system.drawiing; system.data.sqlclient;system.sqlclient.sqltype;空间,你自己加入、
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询