I have a database on my private host, which contains a column for inserting pictures. I completely converted my picture from PictureBox to Binary code and when I go to the database, I can see the binary codes properly. I also programmed a function for converting binary codes to image, and set an event handler for user to click on a cell in DataGridView and all of the values will be displayed on the specific controls.
First I got an error and that error was something like this :
Cannot convert from object to byte[]
I solved this problem by programming a function and convert object binary to byte[], but now, when I try to convert byte[]
(binary array) to image, I face an error and I cannot solve this problem. and problem is :
Parameter is invalid.
Here is my code:
Converting Image to Binary
byte[] ConvertImageToBinary(Image img)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
Convert Object to Binary
byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Convert Binary to Image
Image ConvertBinaryToImage(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
return Image.FromStream(ms);
}
}
And at last, here is my code in
private void DataCustomer_CellContentClick(object sender, DataGridViewCellEventArgs e):
if (DataCustomer.CurrentRow.Cells[9].Value == null)
PictureCustomer.Image = null;
else
{
byte[] ImageByte = ObjectToByteArray(DataCustomer.CurrentRow.Cells[9].Value);
PictureCustomer.Image = ConvertBinaryToImage(ImageByte);
}
Any helpful suggestion would be appreciate.
Thanks in advance