C# 二进制保存读取图片
时间:2010-09-02 来源:itliyi

byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
string str = "server=DA5A491B3F7544B;database=study;uid=sa;pwd=liyi123";
SqlConnection con = new SqlConnection(str);
con.Open();
string sql = "insert into picture ([name],pic) values(@name,@pic)";
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter[] parm = new SqlParameter[]
{
new SqlParameter("@name",SqlDbType.VarChar,50),
new SqlParameter("@pic",SqlDbType.Image,bytes.Length)
};
parm[0].Value = textBox1.Text;
parm[1].Value = bytes;
cmd.Parameters.Add(parm[0]);
cmd.Parameters.Add(parm[1]);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("ok");

string str = "server=DA5A491B3F7544B;database=study;uid=sa;pwd=liyi123";
SqlConnection con = new SqlConnection(str);
con.Open();
SqlCommand cmd=new SqlCommand(sql,con);
SqlDataReader sdr = cmd.ExecuteReader();
if(sdr.HasRows)
{
sdr.Read();
byte[] bytes = (byte[]) sdr["pic"];
MemoryStream ms =new MemoryStream(bytes);
Image image = Image.FromStream(ms);
pictureBox1.Image = image;
}
sdr.Close();
con.Close();

SqlConnection con = new SqlConnection(str);
con.Open();
string sql = "select * from picture where [id]=2";
SqlCommand cmd=new SqlCommand(sql,con);
SqlDataReader sdr = cmd.ExecuteReader();
if(sdr.HasRows)
{
sdr.Read();
byte[] bytes = (byte[]) sdr["pic"];
Response.ContentType = "image/jpg";
Response.OutputStream.Write(bytes,0,bytes.Length);
Response.End();
}
sdr.Close();
con.Close();
//Response.ContentType = "text/HTML"
//Response.ContentType = "image/GIF"
//Response.ContentType = "image/JPEG"
//Response.ContentType = "text/plain"
//Response.ContentType = "image/JPEG"
相关阅读 更多 +