Reputation: 304
I am adding a image in binary format to ms access database with below code. Field data type in database where I store this image is OLE Object
.
The value of reader["Photo"] is as below
(byte[])reader["Photo"] {byte[26]}
byte[] [0] 83 byte [1] 0 byte [2] 121
byte [3] 0 byte [4] 115
byte [5] 0 byte [6] 116
byte [7] 0 byte [8] 101
byte [9] 0 byte [10] 109
byte [11] 0 byte [12] 46
byte [13] 0 byte [14] 66
byte [15] 0 byte [16] 121
byte [17] 0 byte [18] 116
byte [19] 0 byte [20] 101
byte [21] 0 byte [22] 91
byte [23] 0 byte [24] 93
byte [25] 0 byte
private byte[] imageToByteArray()
{
//Store the profile image to the database in binary format
MemoryStream ms = new MemoryStream();
pbProfilePic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
return Pic_arr;
}
Now, I am retrieving this image from database with the help of below code.
OleDbCommand cmd = new OleDbCommand("select * from Employees where EmpId=" + datarecordId + "", conn);
OleDbDataReader reader = cmd.ExecuteReader();
pbProfilePic.Image = byteArrayToImage((byte[])reader["Photo"]);
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
But, I am receiving below error at Image returnImage = Image.FromStream(ms);
Additional information: Parameter is not valid.
Can anyone will help me with this error.
Thanks.
I am using the below code to store image in binary format to MS access database
private byte[] imageToByteArray()
{
//Store the profile image to the database in binary format
MemoryStream ms = new MemoryStream();
pbProfilePic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
return Pic_arr;
}
Upvotes: 0
Views: 1516
Reputation: 676
I get the same error if I just create a byte[] from a random string of characters and use byteArrayToImage. The problem is that your original Image data is bad.
I tried using your methods (imageToByteArray and byteArrayToImage) on a PictureBox with a jpg embedded as the image and it ran with no errors, both converting to a byte[] and then to an Image. It sounds as if something may have corrupted the original data in your picture box.
Upvotes: 0
Reputation: 676
You might try this:
public Image byteArrayToImage(byte[] byteArrayIn)
{
Image retval = null;
using (MemoryStream stream = new MemoryStream(byteArrayIn))
{
retval = (Image)new Bitmap(stream);
}
return retval;
}
Also, as methodMan said, what is the debugger telling you? What is the value of byteArrayIn? Was the MemoryStream properly initialized?
Upvotes: 1