I save my image like this:
//This is in my ImageConverter class:
public static byte[] ConvertImageToByteArray(Image userImage) //Get bytes of the image
{
using (MemoryStream ms = new MemoryStream())
using (Bitmap tempImage = new Bitmap(userImage))
{
tempImage.Save(ms, userImage.RawFormat);
return ms.ToArray();
}
}
//this is in my save button:
sqlCmd.Parameters.Add("@user_image", SqlDbType.VarBinary, 8000).Value =
ImageConverter.ConvertImageToByteArray(pictureBox1.Image);
I retrieve my image by clicking on the datagridview like this:
private void dgvEmpDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex != -1)
{
//Display user image
using (SqlConnection con = new SqlConnection(connectionStringConfig))
using (SqlCommand sqlCmd = new SqlCommand(
"SELECT user_image FROM dbo.Employee_Image
WHERE employee_id=@employee_id", con))
{
con.Open();
sqlCmd.Parameters.Add("@employee_id",
SqlDbType.NVarChar).Value = EmployeeId;
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
pictureBox1.Image = ImageConverter.
ConvertByteArrayToImage((byte[])(reader.GetValue(0)));
}
else
{
pictureBox1.Image = null;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Something is wrong with the selected record!
\nError: { ex.Message }");
}
}
//This is in my ImageConverter class:
public static Image ConvertByteArrayToImage(byte[] buffer) //Get image from database
{
using (MemoryStream ms = new MemoryStream(buffer))
{
return Image.FromStream(ms);
}
}
NOTE: I don't display my image's binary data in my datagridview.
Saving and updating the image (with the users records) works fine.
After saving an image to the database, it does not display properly. But when I load it using OpenFileDialog the image displays just fine.
Loading the image using OpenFileDialog:
When I click a datagridview row to view a user record this is what the pictureBox looks like:
Why is this split in some sort? I have not seen any similar problem/solution about this. Most of them is about "Loading image from the database to pictureBox". But I have already done that.