Retrieve, Resize, and Save Images Back to Access Database Image Field

北城以北 提交于 2020-01-06 08:20:27

问题


I have a table that has a photo column in it, one of the users decided to start saving 20MB images into the field, which consequently caused the database to jump up in size by a factor of 6 in less than a year. So my ultimate goal is to iterate through the table, pull the image, resize and crop it, then save it back to the database.

So my initial thought was this data is being saved as a blob byte array so i'm trying:

public static Bitmap ByteToImage(byte[] blob)
{
    using (var mStream = new MemoryStream())
    {
        mStream.Write(blob, 0, blob.Length);
        mStream.Seek(0, SeekOrigin.Begin);
        var bm = new Bitmap(mStream);
        return bm;
    }
}

//Method
const string myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};  Dbq=E:\SUFDB2006NoPics.mdb;Uid=Admin;Pwd=;";

using(var myConnection = new OdbcConnection())
{
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();
    var dadapter = new OdbcDataAdapter("Select [Contact ID#], [Photo] FROM Contact", myConnection);
    var table = new DataTable();
    dadapter.Fill(table);

    foreach (DataRow row in table.Rows)
    {
       var pht = (byte[])row["Photo"];

       //Tried this 1
       var stream = new MemoryStream(pht); //Parameter is not valid Error.
       pictureBox1.Image = Image.FromStream(stream);

       //Tried this 2
       pictureBox1.Image = ByteToImage(pht);

    }

    this.dataGridView1.DataSource = table; //However this works no problem
    dataGridView1.Refresh();
}

So, interestingly the image column binds to a datagridview no problem. However when I try to bind an individual image row to a picturebox it throws an error. I would put the binary up but its WAY to long. The images are not corrupt as they pull up no problem in the datagridview.

Am i going about this the right way ? Is the data stored as a blob the same way it is in a SQL Server Database ? Also if anyone know of an easier way to do this that would be great. Thanks

Edit

Binary Data in Text File. Too Big to put here is a Link

...and a screenshot:


回答1:


I've had a look at the file you posted, and it looks you're storing your image as an OLE object rather than the bytes of an image. The OLE container prepends a header to your file, which is why you can't decode the byte array directly into an image.

In the case of the file you provided, the bitmap image starts at byte 79 with the BMP header 424D.

This answer has some links that should help you out.



来源:https://stackoverflow.com/questions/21506628/retrieve-resize-and-save-images-back-to-access-database-image-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!