Search code examples
c#winformspicturebox

Error when saving image that was retrieved from DB


Here is the situation:

  1. I could Save() an Employee entry with a picture from PixPictureBox to the database.
  2. If I edit the employee entry and change the picture from the PixPictureBox with a new one, the Update() goes fine.
  3. This is where the error goes, whenever I edit an Employee entry and don't change the PixPictureBox's image, the Update() method throws the following exception:

$exception {"A generic error occurred in GDI+."} System.Runtime.InteropServices.ExternalException

This error is firing from this method:

private byte[] ImageToByteArray(Image imageIn)
{
    using (var ms = new MemoryStream())
    {
        imageIn.Save(ms, imageIn.RawFormat);
        return ms.ToArray();
    }
}

This is my GetParams() method where ImageToByteArray is being used:

private void GetParams()
{
    Ebm.ResetParams();
    Ebm.Params.Id = IdTextBox.Text.GetInt();
    Ebm.Params.EmployeeCode = Ebm.GenerateEmployeeCode();
    Ebm.Params.LastName = LastNameTextBox.Text;
    Ebm.Params.FirstName = FirstNameTextBox.Text;
    Ebm.Params.MiddleName = MiddleNameTextBox.Text;
    Ebm.Params.GenderId = GenderBox.SelectedValue.GetInt();
    Ebm.Params.BirthDate = BirthDatePicker.Value.GetDateTime();
    Ebm.Params.Age = AgeTextBox.Text.GetInt();
    Ebm.Params.Salary = SalaryTextBox.Text.GetDecimal();
    Ebm.Params.StatId = 1;

    if (PixPictureBox.Image != null)
    {
        Ebm.Params.Pics = ImageToByteArray(PixPictureBox.Image);
    }              
}

Here is the method I use to load the picture from the database to PixPictureBox

private Image ByteArrayToImage(byte[] bytesArr)
{
   using (var memstr = new MemoryStream(bytesArr))
   {
          Image img = Image.FromStream(memstr);
          return img;
   }
}

This is how I load it:

private void LoadDetails()
{
    IdTextBox.Text = Ebm.Item.Id.GetString();
    EmployeeCodeTextBox.Text = Ebm.Item.EmployeeCode;
    LastNameTextBox.Text = Ebm.Item.LastName;
    FirstNameTextBox.Text = Ebm.Item.FirstName;
    MiddleNameTextBox.Text = Ebm.Item.MiddleName;
    GenderBox.SelectedValue = Ebm.Item.GenderId;
    BirthDatePicker.Value = Ebm.Item.BirthDate;
    AgeTextBox.Text = Ebm.Item.Age.GetString();
    SalaryTextBox.Text = Ebm.Item.Salary.GetString();

    try
    {
        PixPictureBox.Image = ByteArrayToImage(Ebm.Item.Pics);
    }
    catch (Exception ex)
    {
        PixPictureBox.Image = null;
    }

}

I also get this error from my MemoryStream which I think is related to the exception:

enter image description here


Solution

  • I just needed to change the ByteArrayToImage() method into this:

    private Image ByteArrayToImage(byte[] bytesArr)
    {
        var mem = new MemoryStream(bytesArr);
        Image img = Image.FromStream(mem);
        return img;
    }