求助 我想把图片编程二进制 存入数据库  以及读取  请问这个代码怎么写?

解决方案 »

  1.   

     写数据,数据库中图片ID自增,
     int intImageSize;
      string strImageType;
      Stream ImageStream;
      intImageSize = this.FileUpload1.PostedFile.ContentLength;
      strImageType = this.FileUpload1.PostedFile.ContentType;
      ImageStream = this.FileUpload1.PostedFile.InputStream;
      byte[] imagecontent = new byte[intImageSize];
      int n = ImageStream.Read(imagecontent, 0, intImageSize);  con.open()//打开数据库联接
      sqlcommand cmd=new sqlcommand("INSERT INTO Image(imgtype , imgdata)         
    valueS ( "+ strImageType +", "+ imagecontent  +")",con ); 
    );
      cmd.ExecuteNonQuery();读数据
    Private void Page_Load(object sender, System.EventArgs e)
    {  
    string imgid =Request.QueryString["id"];// 取图片ID
    string sql="SELECT imgdata, imgtype FROM Image WHERE id = " + imgid;  
    SqlCommand command = new SqlCommand(sql, con); 
    con.Open();
    SqlDataReader dr = command.ExecuteReader(); 
    if(dr.Read())
    {   
    Response.ContentType = dr["imgtype"].ToString();   
    Response.BinaryWrite( (byte[]) dr["imgdata"] );  }  
    connection.Close(); }  
      

  2.   

    //存图片这个是SQL的
    scom=new SqlCommand("insert into Photo values('"+ID+"',@ph)",scon);
    FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read);
    byte []bt=new byte[fs.Length]; 
    fs.Read(bt,0,bt.Length);
    fs.Close();
    SqlParameter Spr=new SqlParameter("@ph",SqlDbType.Image,bt.Length,ParameterDirection.Input,   
    false,0,0,null,DataRowVersion.Current,bt);
    scom.Parameters.Add(Spr);
    scom.ExecuteNonQuery();
    //取图片
    SqlCommand scom1=new SqlCommand();
    scom1.Connection=scon;
    scom1.CommandType=CommandType.Text;
    scom1.CommandText="select Photo from Photo where Fid="+bh+"";
    phdr=scom1.ExecuteReader();
    phdr.Read();
    MemoryStream buf=new MemoryStream((byte[])phdr[0]);
    Image image=Image.FromStream(buf,true);
    this.pictureBox1.Image=image;     //显示到pictureBox控件中
    phdr.Close();
      

  3.   

    给你个例子图片保存到数据库和从数据库读取图片并显示(C#) http://www.cnblogs.com/tuyile006/archive/2007/01/08/614718.html