2011-05-11 146 views
1

我无法将图片插入到数据库中。这是我的示例代码。我可以从我的计算机中选择图像并显示在图片框中。一旦我尝试存储显示的图像在图片框中向数据库表示对象引用未设置为对象的实例。c#将图片存储到数据库

这是我的示例代码。

  namespace picutre_storage 
    { 
     public partial class Form1 : Form 
     { 
     public Form1() 
     { 
     InitializeComponent(); 
     } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     try 
     { 

      SqlConnection con = new SqlConnection 
          (@"User ID=sa;Password=password123;Initial Catalog=picuture;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA"); 
      //I have used a table named "tblUsers" and fill the fields 
      SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", con); 

      //Save image from PictureBox into MemoryStream object. 
      MemoryStream ms = new MemoryStream(); 
      pictureBox1.Image.Save(ms,ImageFormat.Bmp); 

      //Read from MemoryStream into Byte array. 
      Byte[] bytBLOBData = new Byte[ms.Length]; 
      ms.Position = 0; 
      ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length)); 

      //Create parameter for insert statement that contains image. 
      SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary,   bytBLOBData.Length, ParameterDirection.Input, false, 
          0, 0, null, DataRowVersion.Current, bytBLOBData); 
      cmd.Parameters.Add(prm); 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
     } 
     catch (Exception ex) 
     { MessageBox.Show(""+ex); } 
    } 

     private void button3_Click(object sender, EventArgs e) 
     { 
     try 
     { 
      //Getting The Image From The System 
      OpenFileDialog open = new OpenFileDialog(); 
      open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 
      if (open.ShowDialog() == DialogResult.OK) 
      { 
       pictureBox2.Image = new Bitmap(open.FileName); 
      } 
     } 
     catch (Exception) 
     { 
      throw new ApplicationException("Failed loading image"); 
     } 
    } 

2.有提前

+0

对于点2:我在救我的数据库,我节约了图像长度的列。 – Marco 2011-05-11 08:08:17

+2

总是将你的SqlConnection对象封装在一个using语句中,否则你将有一个连接池泄漏!:)使用(var cnn = new SqlConnection(...)){....}(在上面的代码中 - 一旦发生错误,您将遇到问题 - 您的连接不会被关闭) – Nathan 2011-05-11 08:09:44

+1

您可以使用ms.ToArray()获取字节数组。无需进行手动分配。 – 2011-05-11 08:11:07

回答

1

在画面box.Thank显示它在东西我看你保存文件为BMP格式,最初那张照片之前就存在任何方式检查图像的大小让我们说jpeg或tiff格式,所以记录被正确插入,但图片引用了一种类型的bmp格式,并且它不存在。 我认为你可以这样做。

  1. ,当你得到你想要的任何 格式的图片,然后在不同的文件夹* (如我的图片\缩略图)创建 缩略图这张照片存储。 *
  2. 获取 图片的扩展名,在 创建缩略图期间将其替换为jpg。
  3. 将其存储在数据库中。
  4. 检索 图片框中的缩略图。你要。

如果你想知道如何创建缩略图(将文件保存为JPG格式,那么最欢迎