Reputation: 5
I realize that this question has been asked before and has answers, but not in this specific way. I have been trying to figure this out for about 7 hours now.
I have a picture that I convert to a byte array to store in an Access database (.mdb)
[Image] -> [byte Array] -> [Access Database(field is an OLE object)] ^ I can do this part fine, done here:
public byte[] ImageToByte(Image img)
{
Bitmap BmpImage = new Bitmap(img);
BmpImage.Save(Application.StartupPath + @"\unmodified.png", System.Drawing.Imaging.ImageFormat.Png);
MemoryStream mStream = new MemoryStream();
PartPhoto.Image.Save(mStream, System.Drawing.Imaging.ImageFormat.Png);
byte[] imgAsByte = mStream.ToArray();
return imgAsByte;
}
Then I Store all of my data in my database like this:
Part p = new Part();
p.PartCode = IPC.Text;
p.PartName = IPN.Text;
p.PartDesc = IDESC.Text;
-->p.PartPhoto = ImageToByte(PartPhoto.Image);
p.PartSize = size;
p.PartWeight = weight;
p.PartType = IPT.Text;
p.LeadTime = ILT.Text;
p.PartCost = ICOST.Text;
p.PartQuantity = IQNT.Text;
d.Insert(p);
The Insert method does this:
command.CommandText = "Insert INTO PartInfo (PartCode, PartName, PartDesc, PartPhoto, PartSize, PartWeight, PartType, LeadTime, PartCost, PartQuantity) VALUES('" + p.PartCode + "', '" + p.PartName + "', '" + p.PartDesc + "', '@Pic', '" + p.PartSize + "', '" + p.PartWeight + "', '" + p.PartType + "', '" + p.LeadTime + "', '" + p.PartCost + "', '" + p.PartQuantity + "')";
command.Parameters.Add("@Pic", p.PartPhoto);
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
It shows up in my database (in the OLE object field) as long binary data. I read from the database into a DataGridView like this:
String query = "SELECT * FROM PartInfo WHERE PartName CONTAINS " + "\"" + PN + "\"";
connection.Open();
da.SelectCommand = new OleDbCommand(query, connection);
da.Fill(dt);
I then call:
PartGrid.DataSource = d.dt;
PartGrid.Refresh();
To refresh the grid.
Here is my problem. I can't read the byte array back from the DataGridView. I tried a couple different ways, always getting the same error: "Parameter is not valid"
byte[] picBytes = (byte[])PartGrid.Rows[row].Cells[3].Value;
MemoryStream ms = new MemoryStream(picBytes);
Image partPic = Image.FromStream(ms); //ERROR: "Parameter is not valid"
Bitmap bmp = new Bitmap(partPic);
bmp.Save(Application.StartupPath + @"\test.png", System.Drawing.Imaging.ImageFormat.Png);
return partPic;
I call convert from byte array to image like this:
PartPhoto.Image = ImageFromByte(e.RowIndex);
Like I said, I've been stuck on this for hours now, and it's getting irritating.
Upvotes: 0
Views: 1862
Reputation:
Try using System.IO.File.ReadAllBytes to convert your image to a byte array and System.IO.File.WriteAllBytes to convert it back.
Upvotes: 0