Solved - Generic Error In GDI occurs when saving jpg image.

Posted on 2009-02-14
Last Modified: 2012-05-06
I am using the attached code to generate a 50 X 50 .jpg thumbnail for an uploaded image, then store the path in a database table.  At our current hosting company, this works without issue.  We are moving to a new company, though, and are redesigning the site, using the new host as a test environment for the new build.  There, this code does not work.  The following error is thrown:

A generic error occurred in GDI+.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

Here is the stack trace:
[ExternalException (0x80004005): A generic error occurred in GDI+.]
   System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630
   System.Drawing.Image.Save(String filename, ImageFormat format) +69
   imageconverter.makethumb() +978
   imageconverter.Page_Load(Object sender, EventArgs e) +7
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

I've looked this up, and it appears to have something to do with the bitmap being locked, but I am unsure how to go about fixing it.  Any help would be appreciated!

oldheight = originalimg.Height

            oldwidth = originalimg.Width

            newheight = (oldheight / oldwidth) * 50

            Dim thumb As New System.Drawing.Bitmap(50, newheight)

            Dim gr_dest As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(thumb)

            gr_dest.DrawImage(originalimg, 0, 0, 50, newheight)

            thumbpath = "/ihost/thumbs/" & itemno(x) & "thumb.jpg"

            thumb.Save(Server.MapPath(thumbpath), ImageFormat.Jpeg)

            cmdstr = "UPDATE DataAuctions SET Thumb = '" & thumbpath & "' WHERE ID =" & itemno(x)

            sqlcommand = New OleDbCommand(cmdstr, myconn)

            rs = sqlcommand.ExecuteReader


Open in new window

Question by:kmerlo
    LVL 12

    Expert Comment

    I think the Server.Mappath requires only the path, but, thumbpath gives the file name as well
                thumbpath = "/ihost/thumbs/" & itemno(x)
                thumb.Save(Server.MapPath(thumbpath)  & "thumb.jpg", ImageFormat.Jpeg)

    what is coming as itemno(x), is it a folder name or you want to prefix it with the thumb.jpg?
    LVL 12

    Expert Comment


    Author Comment

    Itemno (x) is an integer- the unique field from the database- you are correct, I am using it as a prefix for the filename.  The filename should be "123thumb.jpg", "125thumb.jpg", etc.
    LVL 22

    Accepted Solution

    If the same code works on the old hosting site but not working on your new hosting site, then it looks to me a write permission issue. Check if your application has the "write" permission to the folder you are trying to save the image.
    LVL 15

    Assisted Solution

    as prairiedog mentioned, the generic GDI error like that usually means a permissions issue.

    Check to ensure that the "thumbs" folder has modify/write access for the user account.

    Depending on how the server is set up, it could be the Network Service account, or it could be the IIS WP user.

    Author Comment

    I've contacted the hosting company...hopefully they won't have any problem with giving the permissions to the folder...
    LVL 5

    Expert Comment

    SOLUTION: A generic error occurred in GDI+
    I'm not sure "WHY" this works ... but it solved my problems.
    Caveat: Below uses [ImageFormat.Bmp] If you're reading/writing another format, you'll need to tweak.
    Caveat: During the write operation a temporary file named [temporaryToDefeatGDIerror.bmp] is momentarily created, copied then deleted.
    Here's a general Function class which does the real work.
    class fn
        public static void SaveImageToFile(string DrvPath, string FileExt, Bitmap bm)
            string actualDPFEwanted = DrvPath + FileExt;
            if (File.Exists(actualDPFEwanted) == true) File.Delete(actualDPFEwanted);
            string tempDPFE = DrvPath + "temporaryToDefeatGDIerror.bmp";
            if (File.Exists(tempDPFE) == true) File.Delete(tempDPFE);
            bm.Save(tempDPFE, ImageFormat.Bmp);
            File.Copy(tempDPFE, actualDPFEwanted);
        public static Bitmap GetImageDisconnectedFromFile(string DrvPathFileExt)
            Image Iret = (Image)new Bitmap(1,1);
            if (File.Exists(DrvPathFileExt) == true)
                FileInfo FI = new FileInfo(DrvPathFileExt);
                if (FI.Length > 1)
                    Stream s = File.Open(DrvPathFileExt, FileMode.Open);
                    Iret = Image.FromStream(s);
            Bitmap BM = new Bitmap(Iret);
            GC.Collect(0, GCCollectionMode.Forced);
            return BM;
    and here's a sample of how I use each's
    private void ReadOne()
        string DP = String.Format("{0}\\ImageSink\\", Path.GetDirectoryName(Application.ExecutablePath));
        if (!Directory.Exists(DP)) Directory.CreateDirectory(DP);
        if (File.Exists(DP + "a.bmp") == true) picturebox1.Image = fn.GetImageDisconnectedFromFile(DP + "a.bmp");
    private void WriteOne()
        string DP = String.Format("{0}\\ImageSink\\", Path.GetDirectoryName(Application.ExecutablePath));
        if (!Directory.Exists(DP)) Directory.CreateDirectory(DP);
        if (!(picturebox1.Image == null)) fn.SaveImageToFile(DP, "a.bmp", (Bitmap)picturebox1.Image);
    Enjoy y'all
    Frederick Volking

    Expert Comment

    I've set the permissions and still am getting this same error when I try to use an XCeed tool.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    A Change in PHP Behavior with Session Write Short Circuit ( (Winter 2014)** With the release of PHP 5.6 the session handler changed in a way that many think should be considered a bug.  See the note …
    What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
    Learn how to create interesting presentations by including videos to keep your audience engaged using Prezi. Select "Insert" from the top menu in your Prezi editor: Select "YouTube Video": Paste the video URL into the prompt: "Select "Insert":…
    Learn how to use the remote presentation tool in Prezi to allow you to harness the power of this cloud based presentation platform. You can show your presentation with a remote audience using this free tool.

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now