郁闷了半天,原来是这个问题:关于C#中关于图片保存到数据库以及将数据库中的图片显示到PictureBox。

能够保存图片到数据库中去,但是显示总是出错,提示:无效参数。郁闷了半天,在csdn上找了很多的资料但是还是不行。后来看了数据库中的内容,发现是不是长度不对,因为我将图片保存时的byte[]的Length都很大(上百上千甚至更大),但是从数据库取出的byte[]的Length只有13。后来改了储存的长度参数后终于好了。总算没有白费功夫。搞了好几个小时。

不过还好,在冠军杯前一个多小时搞完了,正好可以安心的看一下拜仁和Chelsea的比赛了(第一回合切4:2占先)。

附:代码

  private System.Windows.Forms.PictureBox pictureBox1;
  private System.Data.SqlClient.SqlCommand cmdExecute;
  private System.Data.SqlClient.SqlConnection connEmployee;
  private Bitmap image;
  private byte[] buffer;

private void ShowMyImage(string fileToDisplay, int xSize, int ySize)
  {
   // Sets up an image object to be displayed.
   if (image != null)
   {
    image.Dispose();
   }

   // Stretches the image to fit the pictureBox.
   pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage ;
   image = new Bitmap(fileToDisplay);
   pictureBox1.ClientSize = new Size(xSize, ySize);
   pictureBox1.Image = (Image) image ;
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   OpenFileDialog openFileDialog = new OpenFileDialog();
   openFileDialog.Title = "请选择照片";
   openFileDialog.ReadOnlyChecked = true;
   openFileDialog.ShowReadOnly = true;
   openFileDialog.Filter = "所有图片文件|*.*|JPEG(*.JPG;*.JPEG;*.JPEe;*.JFIF)|*.JPG;*.JPEG;*.JPEe;*.JFIF|位图文件(*.BMP)|*.BMP|GIF(*.GIF)|*.GIF";

   string pictureName = "";
   if (openFileDialog.ShowDialog() == DialogResult.OK)
   {
    pictureName = openFileDialog.FileName;
    this.ShowMyImage(pictureName, 112, 130);
   }

   if (pictureName != "")
   {
    FileStream stream = new FileStream(pictureName, FileMode.Open, FileAccess.Read);
    buffer = new byte[stream.Length];
    stream.Read(buffer, 0, (int)stream.Length);
    stream.Close();
   }

   this.cmdExecute.CommandText = @"INSERT INTO Photo_Test(Photo) values(@Photo)";
   this.cmdExecute.Parameters.Add("@Photo", SqlDbType.Image, buffer.Length, "Photo");
   this.cmdExecute.Parameters["@Photo"].Value = buffer;
   if (this.connEmployee.State == ConnectionState.Closed)
    this.connEmployee.Open();
   this.cmdExecute.ExecuteNonQuery();
  }

  private void button2_Click(object sender, System.EventArgs e)
  { 
   SqlDataAdapter da = new SqlDataAdapter("Select * from Photo_Test WHERE ID = 20", this.connEmployee);
   DataSet ds = new DataSet();
   da.Fill(ds);
   DataTable dt = ds.Tables[0];
   byte[] b = (byte[])dt.Rows[0][1];

   if(b.Length > 0)
   {
    MemoryStream stream = new MemoryStream(b, true);
    stream.Write(b, 0, b.Length);
     
    image=new Bitmap(stream);
    
    stream.Close();
    this.pictureBox1.Image = image;
   }
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值