Reputation: 39
I am trying to save a number, date time and an image to access database using c# application. i have written a function which converts image to base64string format and then i use the function to get image as a string and later save it. I however get an error saying 'argument NULL exception was unhandled'. this error occurs at the following line in the code image.Save(stream, image.RawFormat);*
my code is as follows:
private void save_Click(object sender, System.EventArgs e)
{
string oneimg=ImageToBase64String(pictureBox1.Image);
string twoimg=ImageToBase64String(pictureBox2.Image);
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Windows\roadsafety.accdb;Jet OLEDB:Database Password=sudeep;");
con.Open();
try
{
// con.Open();
OleDbCommand cmd = new OleDbCommand("insert into dashboard(id,dtime) values('" + textBox2.Text + "','" + DateTime.Now.ToString() + "','" + oneimg + "','" + twoimg + "')", con);
cmd.ExecuteReader();
MessageBox.Show("Succesfully saved");
}
catch (Exception k)
{
MessageBox.Show(k.ToString());
}
}
private string ImageToBase64String(Image image)
{
using (MemoryStream stream = new MemoryStream())
{
image.Save(stream, image.RawFormat);
return Convert.ToBase64String(stream.ToArray());
}
}
Please help
Upvotes: 0
Views: 9954
Reputation: 2210
OleDbConnection myConnection = null;
try
{
//save image to byte array and allocate enough memory for the image
byte[] imagedata = image.ToByteArray(new Atalasoft.Imaging.Codec.JpegEncoder(75));
//create the SQL statement to add the image data
myConnection = new OleDbConnection(CONNECTION_STRING);
OleDbCommand myCommand = new OleDbCommand("INSERT INTO Atalasoft_Image_Database (Caption, ImageData) VALUES ('" + txtCaption.Text + "', ?)", myConnection);
OleDbParameter myParameter = new OleDbParameter("@Image", OleDbType.LongVarBinary, imagedata.Length);
myParameter.Value = imagedata;
myCommand.Parameters.Add(myParameter);
//open the connection and execture the statement
myConnection.Open();
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
Link:
Upvotes: 0