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

时间:2011-06-23 03:21:39

标签: c# image ms-access

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

3 个答案:

答案 0 :(得分:3)

我将图像转换为byte []和。然后将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;
}

答案 1 :(得分:0)

以下链接可以帮助您:

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

                     }

希望这会有所帮助......

答案 2 :(得分:0)

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数据库文件。