将图像保存到access数据库中

问题描述 投票:0回答:1

我正在尝试使用 C# 应用程序保存数字、日期时间和图像以访问数据库。 我编写了一个将图像转换为 base64string 格式的函数,然后使用该函数将图像获取为字符串,然后保存它。 然而,我收到一条错误消息“参数 NULL 异常未处理”。此错误发生在代码中的以下行 图像.保存(流,图像.RawFormat);*

我的代码如下:

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

请帮忙

c# ms-access-2007
1个回答
0
投票
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();
}

链接:

http://social.msdn.microsoft.com/Forums/en-US/ef838689-5484-4f23-bc3b-ce11c578c524/c-oledb-accessmdb-storing-and-retriving-images?forum=adodotnetdataproviders

© www.soinside.com 2019 - 2024. All rights reserved.