0

In this code i wanted to save the image in picturebox1 in database using linqtosql ..... but getting some exceptions in converting a image to byte array

Exception is "System.NullReferenceException: Object reference not set to an instance of an object."

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();
    }

}
cdhowie
  • 133,716
  • 21
  • 261
  • 264
Usman Asif
  • 13
  • 1
  • 2

2 Answers2

1

I suspect the problem is that pictureBox.Image is null when you reference it. You are setting pictureBox.ImageLocation but not actually loading the image. Add a call to pictureBox.Load() immediately after setting pictureBox.ImageLocation.

Brian O''Byrne
  • 530
  • 2
  • 10
0

When you create the Memorystream, you have to associate with bytes[], for example

byte[] buf = new byte[4096];

Then you could you using (MemoryStream ms = new MemoryStream(buf))

So calculate an upper bound for the image size in bytes, and then associate a MemoryStream to an array containing that many bytes.

Srikant Krishna
  • 861
  • 5
  • 10