【问题标题】:Saving an image into sql server 2008 database issue? [duplicate]将图像保存到 sql server 2008 数据库问题? [复制]
【发布时间】:2015-11-06 13:26:29
【问题描述】:

我在尝试从 c# 应用程序保存图像时遇到以下错误消息。到 SQL Server 2008 数据库。

请注意,加载工作正常,问题出在保存时。

请帮忙??

无法将参数值从图片框转换为字节[]

保存图片的代码

 private void saveLogo()
            {

         SqlConnection   conn = new SqlConnection(dbcon.ReturnConnection());

            try
            {
         SqlCommand sqlCommand1 = conn.CreateCommand();
                sqlCommand1.CommandText = "INSERT INTO OrgLogo(ID,LogoName,Picture) values(@ID,@Name,@Picture)";

                conn.Open();
                if (sqlCommand1.Parameters.Count == 0)
                {                  
                   sqlCommand1.Parameters.Add("@ID", System.Data.SqlDbType.Int, 4);
                   sqlCommand1.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 50);
                  sqlCommand1.Parameters.Add("@Picture", System.Data.SqlDbType.Image);
                }
          sqlCommand1.Parameters["@ID"].Value =Convert.ToInt32( editID.Text);
           sqlCommand1.Parameters["@Name"].Value = editName.Text;
           sqlCommand1.Parameters["@Picture"].Value = pictureBox1;

           sqlCommand1.ExecuteNonQuery();             

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                conn.Close();

            }
        }

打开图片文件的代码

protected void LoadLogoPic()
        {

            this.openFileDialog2.ShowDialog();

            string strFn = this.openFileDialog2.FileName;
                this.pictureBox1.Image = Image.FromFile(strFn);
                this.openFileDialog2.Filter = "All Files|*.*|BMP Files|*.bmp|JPG Files|*.jpg"; 
                FileInfo fiImage = new FileInfo(strFn);
              m_lImageFileLength = fiImage.Length;
                FileStream fs = new FileStream(strFn, FileMode.Open, FileAccess.Read, FileShare.Read);
                m_barrImg = new byte[Convert.ToInt32(this.m_lImageFileLength)];
                int iBytesRead = fs.Read(m_barrImg, 0, Convert.ToInt32(this.m_lImageFileLength));
                fs.Close();



        }

【问题讨论】:

  • 您正试图存储 PictureBox 控件 而不是图像的数据。如果您将图像的字节数(即m_barrImg)作为参数值传递,则该语句至少适用于小图片。对于较大的,您必须使用

标签: c# sql-server-2008 filestream


【解决方案1】:

试试这个方法;

Image img = picturebox1.Image();
byte[] arr;
ImageConverter converter = new ImageConverter();
arr=(byte[])converter.ConvertTo(img, typeof(byte[]));

command.CommandText = "INSERT INTO ImagesTable (Image) VALUES('" + arr + "')";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();

【讨论】:

  • 该语句最终将作为'INSERT INTO ImagesTable (Image) VALUES('System.Byte[]')'。使用字符串连接从不解决 SQL 问题,在这种情况下它只是添加新问题。事实上,如果传递的是实际的字节数组而不是控件,则 OP 的代码会起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多