在CSharp中,怎样将PictureBox图片(来自文件)保存到后台SQL数据库中,及如果从SQL数据库中读取图片,并显示到PictureBox控件中?

解决方案 »

  1.   

    保存
    sql="insert into p_ry_photo(id,photo) values ('"+id+"',@i)";
    SqlCommand cmd=new SqlCommand(sql,CommonVar.SqlConDataBase);
    MemoryStream s = new MemoryStream();
    picPhoto.Image.Save(s,System.Drawing.Imaging.ImageFormat.Jpeg);
    byte[] b = s.ToArray();
    s.Close();
    cmd.Parameters.Add("@i",SqlDbType.Image,(int)b.Length);
    cmd.Parameters["@i"].Value=b;
    cmd.ExecuteNonQuery();
      

  2.   

    private void Readphoto(string id)
    {
     try
      { //读取图象
        string ls_sql="select photo from p_ry_photo where id='"+id+"'";
        this.picPhoto.Image=null;
        this.picPhoto.Refresh();
        SqlCommand cmd=new SqlCommand(ls_sql,CommonVar.SqlConDataBase);
        SqlDataReader reader=cmd.ExecuteReader();
        while(reader.Read())
          {
            byte[] b = (byte[])reader[0];
            MemoryStream s = new MemoryStream(b);
            Bitmap bmp = new Bitmap(s);
            System.Drawing.Image image = bmp;
            picPhoto.Image = image;
            s.Close();
            }
         reader.Close();
       }
    catch(Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
    }
      

  3.   

    数据库中字段类型:image(sqlserver),blob(oracle)
    /// <summary>
    /// 将图片转换成字节数组
    /// </summary>
    /// <param name="img"></param>
    /// <returns></returns>
    public static byte[] ImageToByte(Image img)
    {
    byte[] byt = null;
    ImageConverter imgCvt = new ImageConverter();
    object obj = imgCvt.ConvertTo( img,typeof(Byte[]));
    byt = (Byte[])obj;
    return byt;
    }
    /// <summary>
    /// 将字节数组转换成图片
    /// </summary>
    /// <param name="bytImage"></param>
    /// <returns></returns>
    public static Image ByteToImage( byte[] bytImage )
    {
    Image img = null;
    ImageConverter imgCvt = new ImageConverter();
    object obj = imgCvt.ConvertFrom(bytImage);
    img = (Image)obj;
    return img;
    }
      

  4.   

    哪个“CommonVar.SqlConDataBase”有谁知道是什么类吗?所在的Namespace 呢?
      

  5.   

    可能是他自己寫的一個類,CommonVar.SqlConDataBase主要是提供數據庫聯結字浮串的.
    正確的都讓你們說完了
      

  6.   

    运行到此:object obj = imgCvt.ConvertFrom(bytImage);
    提示:引用了无效参数。谁知怎么回事啊?
      

  7.   

    未处理的“System.ArgumentException”类型的异常出现在 system.drawing.dll 中。其他信息: 使用了无效参数(此提示)