2013-02-19 68 views
0

在此代码我想使用linqtosql保存在数据库picturebox1图像的一个实例.....但得到一些例外的图像转换为字节数组System.NullReferenceException:对象不设置为一个对象

异常是“System.NullReferenceException:未将对象引用设置为对象的实例。”

private void button1_Click(object sender, EventArgs e) 

{ 
    DataClasses1DataContext dc = new DataClasses1DataContext(); 
    try 
    { 
     string signname = textBox1.Text; 
     string imageurl = textBox2.Text; 
     pictureBox1.ImageLocation = imageurl; 
    // byte[] file_byte = new byte[1000]; 
     // Image newimage = new Image(pictureBox1.Image); 
    ///Error comes here 
    byte[] file_byte = ImageToByteArray(pictureBox1.Image); 
     System.Data.Linq.Binary file_binary = new               System.Data.Linq.Binary(file_byte); 


     Sign_Table obj = new Sign_Table() 
     { 
      Sign_Name = signname, 
      Sign_Image = file_binary, 

     }; 
     dc.Sign_Tables.InsertOnSubmit(obj); 

    } 
    finally 
    { 
     dc.SubmitChanges(); 
    } 

} 
private byte[] ImageToByteArray(Image imageIn) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    { 

      // Error comes here 
     imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); 
     return ms.ToArray(); 
    } 

} 
+1

几乎所有的'NullReferenceException'都是一样的。请参阅“[什么是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”的一些提示。 – 2013-02-19 17:15:47

+2

你在调试器中运行过吗?它会告诉你究竟哪个对象是空的。 – ChrisF 2013-02-19 17:15:50

+0

可能是错误引发ImageToByteArray函数 – Utkarsh 2013-02-19 17:18:17

回答

1

我怀疑问题是pictureBox.Image在你引用它时是null的。你正在设置pictureBox.ImageLocation,但实际上并没有加载图像。 在设置pictureBox.ImageLocation后立即添加对pict​​ureBox.Load()的调用。

+0

谢谢你,你是天才........... – 2013-02-19 17:34:07

0

在创建MemoryStream的,则必须用字节[]相关联,例如

字节[] BUF =新的字节[4096];

那么你可以你 使用(MemoryStream的MS =新的MemoryStream(BUF))

所以计算的上界以字节为单位的图像的大小,然后一个MemoryStream到阵列包含很多字节相关联。

相关问题