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();
}
}
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.