Solving: A generic error occurred in GDI+. in C#

I was creating an image in C# by using code similar to:

public void SaveImage()
{
byte[] byteArray = null; // Put the bytes of the image here....
Image result = null;
ImageFormat format = ImageFormat.Png;
using (MemoryStream ms = new MemoryStream(byteArray))
{
result = Image.FromStream(ms);
}
using (Image imageToExport = result)
{
string filePath = string.Format(@"C:\Temp\Myfile.{0}", format.ToString());
imageToExport.Save(filePath, format);
}
}

This resulted in the error: "A generic error occurred in GDI+."

 

The error was resolved, after changing the code to:

public void SaveImage()
{
byte[] byteArray = null; // Put the bytes of the image here....
Image result = null;
ImageFormat format = ImageFormat.Png;
  result = new Bitmap(new MemoryStream(byteArray));


using (Image imageToExport = result)
{
string filePath = string.Format(@"C:\Temp\Myfile.{0}", format.ToString());
imageToExport.Save(filePath, format);
}
}

 

I found the solution at: http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream

4 Comments

  1. Dino

    Hello
    I find on web that you have similar error like I get now and I don’t know how to resole.
    In my C#.NET application I catch webcam picture in pictureBox and try to save on disk with SaveFileDialog, but I get always the same error “A generic error occurred in GDI+”. Code is blow, if you can help…
    =======================
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.InitialDirectory = @”slike”;
    sfd.Filter = “*.jpg|*.jpg”;
    sfd.Title = “Spremi sliku kao…”;
    sfd.FilterIndex = 1;
    if (sfd.ShowDialog() == DialogResult.OK)
    {
    try
    {
    using (Bitmap bitmap = new Bitmap(pictureBox1.Image))
    {
    bitmap.Save(sfd.FileName, ImageFormat.Jpeg);
    sfd.Dispose();//To Do…. isprobaj
    bitmap.Dispose();//To Do…. isprobaj
    }
    MessageBox.Show(“Slika je spremljena! “, “Spremanje slike”,
    MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception ex)
    {
    MessageBox.Show(“GreŇ°ka pri spremanju slike: \n” + ex.Message);
    }
    finally
    {
    sfd.Dispose();// to check…..
    }
    }
    sfd.Dispose();// to check…..
    button6.Enabled = true;
    button7.Enabled = false;
    button8.Enabled = false;
    button9.Enabled = false;
    pictureBox1.Image = Image.FromFile(“nemaslike.jpg”);
    this.WebCamCapture.Stop();
    textBox1.Focus();

  2. punit

    How to Put the bytes of the image ?….
    i am getting this error

    An exception of type ‘System.ArgumentNullException’ occurred in mscorlib.dll but was not handled in user code

    Additional information: Buffer cannot be null.

Leave a Reply

Your email address will not be published. Required fields are marked *