none
Bitmap.Save 'A generic error occurred in GDI+'

    Question

  • Hello All,

    I was just going to play around by generating some bitmaps programatically.

    I started off with this simple example, expecting everything to go smoothly, but have run into a strange error.

    The following code is by no means good, just something simple and complete I would expect to work:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;

    namespace BitmapOutput
    {
        public partial class Form1 : Form
        {
            /// <summary>
            /// The picture i am drawing
            /// </summary>
            System.Drawing.Bitmap myBitmap;

            /// <summary>
            /// Graphics object for drawing
            /// </summary>
            System.Drawing.Graphics myGrafx;

            public Form1()
            {
                InitializeComponent();

                this.myBitmap = new Bitmap(800, 600);

                this.myGrafx =                 System.Drawing.Graphics.FromImage(this.myBitmap);

                this.DrawPicture();

                this.ShowPicture();

                this.SavePicture();
            }

            public void DrawPicture()
            {
                this.myGrafx.DrawEllipse(
                    new Pen(System.Drawing.Color.AliceBlue),                 new Rectangle(0, 0, 100, 100));

            }

            public void ShowPicture()
            {
                this.pictureBox1.Image = this.myBitmap;
            }

            public void SavePicture()
            {
                this.myBitmap.Save("Output\\out.bmp" ,                    System.Drawing.Imaging.ImageFormat.Bmp );
            }
        }
    }

    This runs fine until the SavePicture(...) function is called.

    I get the exception:
    "A generic error occurred in GDI+."

    at the this.myBitmap.Save(...); line.

    Most likely there is some detail that I have overlooked, and I appreciate it if anyone could point out to me what I could do to fix it.

    But, I'd like to think that this code would work, it makes sense, and requires little effort, that should be one of the goals of .net

    Any help or ideas are greatly appreciated!

    P.S. how do I use 'code' tags?
    Sunday, August 13, 2006 8:50 PM

Answers

  • it happens with me - its a minor bug which should *hopefully* be fixed in SP1 of .NET 2.0.

    sometimes this error occurs, sometimes it doesnt

    sometimes putting a Thread.Sleep() (for about 30 ms) helps it just before the save

    Monday, August 14, 2006 12:24 AM
    Moderator

All replies

  • it happens with me - its a minor bug which should *hopefully* be fixed in SP1 of .NET 2.0.

    sometimes this error occurs, sometimes it doesnt

    sometimes putting a Thread.Sleep() (for about 30 ms) helps it just before the save

    Monday, August 14, 2006 12:24 AM
    Moderator
  • Hello,

     

    Perhaps too late but for who ever encounters the same problem, I've found a solution (work around) this error bij copying the bitmap to an new one

     

            public void SavePicture()
            {

                Bitmap bm = new Bitmap(this.myBitmap)
                bm.Save("Output\\out.bmp" ,System.Drawing.Imaging.ImageFormat.Bmp );
            }

    Do'n ask me why but it works....

     

    Greets,

    Jean Paul

    ON7AMI

    • Proposed as answer by Dalibor Prka Thursday, January 21, 2010 2:24 AM
    Friday, February 09, 2007 9:19 AM
  • Thanks very much.

    That fixed my generic error too.

    Monday, July 02, 2007 6:44 PM
  • Perfect. Bizarre, but perfect.
    Friday, July 27, 2007 8:47 PM
  • Thanks so much.. was struggling to resolve this for the last 1 hour...

     

    Friday, August 03, 2007 9:35 PM
  • Great, thanks for posting this work around  

     

    Sunday, October 28, 2007 9:16 PM
  • Worked for me as well, THANKS.
    N I C K
    Friday, August 08, 2008 9:49 PM
  • check this link for answer
    http://blog.vishalon.net/Post/70.aspx
    Saturday, August 09, 2008 12:41 PM
  • thankyou
    Friday, September 26, 2008 5:52 PM
  • Thank you Jean Paul.
    This fixed my problem too.
    Monday, August 17, 2009 3:10 PM
  • Two years later, and let the thank yous continue.  This worked for me too!
    Saturday, December 26, 2009 7:26 PM
  • Seems the second bitmap fix is still applicable in Fx 3.5, even with the Bitmap.Save(stream,format) overload, too!  Thanks for the help. 
    Thursday, July 01, 2010 2:25 AM
  • Actually, the fix is to properly dispose of your objects in order.  This is one advantage of C#, with the using() syntax:

    // new image with transparent Alpha layer
    using (var bitmap = new Bitmap(330, 18, PixelFormat.Format32bppArgb))
    {
    	using (var graphics = Graphics.FromImage(bitmap))
    	{
    		// add some anti-aliasing
    		graphics.SmoothingMode = SmoothingMode.AntiAlias;
    
    		using (var font = new Font("Arial", 14.0f, GraphicsUnit.Pixel))
    		{
    			using (var brush = new SolidBrush(Color.White))
    			{
    				// draw it
    				graphics.DrawString(user.Email, font, brush, 0, 0);
    			}
    		}
    	}
    
    	// setup the response
    	Response.Clear();
    	Response.ContentType = "image/png";
    	Response.BufferOutput = true;
    
    	// write it to the output stream
    	bitmap.Save(Response.OutputStream, ImageFormat.Png);
    	Response.Flush();
    }
    
    

    Notice how I dispose (end the using) of the graphics parameter, before I save it?  You don't have to use the using() statements, just call Dispose() at the end of the scope I show above.

    I ran into this problem today on Azure (works locally in the cloud, just an Azure 1.3 thing!), and I saw the link to the blog post above.  That was a good link, as it pointed me in the direction of disposing the graphics earlier.

    But, there is no point of increasing hte memory usage of two bitmaps if you dispose of your graphics properly before saving.


    http://eduncan911.com
    • Proposed as answer by eduncan911.com Wednesday, July 14, 2010 10:14 PM
    Wednesday, July 14, 2010 10:14 PM
  • It doesn't seem to be to do with the order of disposal - am executing code like this twice in quick succession and seeing the bug  ('cos that what it's looking like) the second time irrespective of what gets disposed when and which overload of Save I call. Have resorted to using the bitmap clone technique as described above - it's kludgey but it works, for which my thanks!
    Saturday, January 15, 2011 6:03 PM
  • Because this thread seems to get a lot of visits, it might be worth adding this proposition from JohnWein to fix the problem instead of working around it...
    GDI+ keeps a lock on files from which an image was contructed. To avoid the lock, construct the image from a MemorySteam:
     MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileName)); 
    Image img = Image.FromStream(ms);



    "The improbable we do, the impossible just takes a little longer." (Steven Parker)
    • Proposed as answer by msr681 Wednesday, August 03, 2011 8:14 AM
    • Unproposed as answer by msr681 Wednesday, August 03, 2011 8:14 AM
    • Proposed as answer by JB1112 Thursday, March 08, 2012 2:32 PM
    Thursday, March 17, 2011 8:00 AM
  • I think it is not a code problem, it is due to installed components, I also experienced the same issue and is solved by self after uploading on a regular server.
    C#.net developer
    Wednesday, August 03, 2011 8:14 AM
  • Thanks a ton Jan Var der Haegen! These Two code lines saved my day :)
    Thursday, March 08, 2012 2:32 PM
  • Thanks Jean Paul.

    You saved my day too.

    Tuesday, September 04, 2012 7:37 PM
  • (Five years, and two versions of Visual Studio, later...)

    Brilliant !

    Ridiculously, you're absolutely right.   Attempting to save using the original Bitmap failed, but with this SavePicture() function, it worked a treat.   

    Many thanks !


    Friday, February 08, 2013 10:41 AM
  • I might also depend on where your output is to.  Directly to C: was the cause of the error for me - rights issue?  Changed from the root to a subfolder and worked fine without the extra function.
    Saturday, March 02, 2013 8:26 PM
  • I hit this when attempting to save to a non-existent folder.  Make sure you call

    Directory.CreateDirectory(Path.GetDirectoryName(fileName));

    before you try to save.

    Saturday, March 16, 2013 8:25 AM
  • Because this thread seems to get a lot of visits, it might be worth adding this proposition from JohnWein to fix the problem instead of working around it...
    GDI+ keeps a lock on files from which an image was contructed. To avoid the lock, construct the image from a MemorySteam

    In my case the problem was that from time to time was executed a code that has tried to save img to file and there was undisposed image that has been read from this file.

    var img = Bitmap.Load("file1");
    // no img dispose was called
    img2.Save("file1"); // GDI+ exception here

    I've added img.Dispose call before img2.Save and it has started to work.

    Thank you



    Regards

    Thursday, June 19, 2014 11:39 AM
  • Hello,

     

    Perhaps too late but for who ever encounters the same problem, I've found a solution (work around) this error bij copying the bitmap to an new one

     

            public void SavePicture()
            {

                Bitmap bm = new Bitmap(this.myBitmap)
                bm.Save("Output\\out.bmp" ,System.Drawing.Imaging.ImageFormat.Bmp );
            }

    Do'n ask me why but it works....

     

    Greets,

    Jean Paul

    ON7AMI

    Thanks friend

    Allow time to reverse.

    Saturday, August 09, 2014 10:43 AM