如何将图像插入Microsoft Access数据库

本文关键字:Microsoft Access 数据库 插入 图像 | 更新日期: 2023-09-27 18:00:11

我正在尝试转换图像以插入C#中的Microsoft Access数据库。Net Windows窗体。而且我还想删除和更改图像。但我不知道该怎么做。请为我写一段代码。

如何将图像插入Microsoft Access数据库

我会将图像转换为byte[]和。然后将字节[]转换回图像。

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
public static Image ImageFromByte(byte[] image)
{
    ImageConverter ic = new ImageConverter();
    Image img = (Image)ic.ConvertFrom(image);
    return img;
}

以下链接将帮助您:

http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/c3fae255-9d2e-45e9-b830-58d544fc43ee/

转换将在上述链接的以下行中进行:

using ( FileStream fs = fi.OpenRead() )
                     {
                           bData = new byte[fi.Length];
                           int nReadLength = fs.Read( bData,0, (int)(fi.Length) );
                     }

希望这能帮助。。。

using (var connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'BlankDatabase.mdb"))
{
    connection.Open();
    // Create table
    using (var command = connection.CreateCommand())
    {
        command.CommandText = @"
            CREATE TABLE FileTable (
                FileName VARCHAR(255),
                File IMAGE)
            ";
        command.ExecuteNonQuery();
    }
    var imageContent = File.ReadAllBytes(@"C:'logo.png");
    // upload image to the table
    using (var command = connection.CreateCommand())
    {
        command.CommandText = @"
            INSERT INTO FileTable (FileName, File)
            VALUES (@FileName, @File)
            ";
        command.Parameters.AddWithValue("@FileName", "Logo");
        command.Parameters.AddWithValue("@File", imageContent);
        command.ExecuteNonQuery();
    }
    // retreive image from the table
    using (var command = connection.CreateCommand())
    {
        command.CommandText = @"
            SELECT File
            FROM FileTable
            WHERE FileName = 'Logo'
            ";
        var readImageContent = (byte[])command.ExecuteScalar();
        File.WriteAllBytes(@"C:'logo1.png", readImageContent);
    }
    // alter image from the table
    using (var command = connection.CreateCommand())
    {
        command.CommandText = @"
            UPDATE FileTable
            SET File = @File
            WHERE FileName = 'Logo'
            ";
        command.Parameters.AddWithValue("@File", imageContent);
        command.ExecuteNonQuery();
    }
    // delete image from the table
    using (var command = connection.CreateCommand())
    {
        command.CommandText = @"
            DELETE FROM FileTable
            WHERE FileName = 'Logo'
            ";
        command.ExecuteNonQuery();
    }
}

在此代码中,BlankDatabase.mdb是一个空的MS Access数据库文件。