C#: The dreaded “A generic error occurred in GDI+.” Exception

moondaddy 911 Reputation points
2022-10-19T03:01:08.97+00:00

I have googled this a lot but not found any good solutions. Users upload images to the server via an Asp.Net API and the code below saves the files to disk. This works most of the time (1000s) but sometimes I get this GDI exception.

This uses .net 4.8, Asp.Net, and fails on both IIS for Windows Server 2019 an Windows 11.

Here’s my code:

string originalTmpPath = "D:\somePath\imageName.jpg"  
var obj = JsonConvert.DeserializeObject<Issue_ModelV2>(requestContent);  
  
byte[] parms = Convert.FromBase64String(obj.ImageData);  
using (var ms = new MemoryStream(parms))  
{  
    using (var img = System.Drawing.Image.FromStream(ms))  
    {  
        //Was getting this error:  ExternalException: A generic error occurred in GDI+.  
        //so I added the next line to see if it helped.  
        System.Drawing.Image copy = img;  
     
   // Get exception on this line  
        copy.Save(originalTmpPath, System.Drawing.Imaging.ImageFormat.Jpeg);  

I also tried this but go the same GDI exception:

System.Drawing.Image copy = img;  
var tmpImg = new Bitmap(copy);  
tmpImg.Save(originalTmpPath, ImageFormat.Jpeg);  

NOTE: If I run this in a .net 4.8 console app it runs fine. This is the code for that:

static void ProcessImage()  
{  
    string sourcePath = @"D:\Apps\zDeleteme\GDI Exception\GDI Exception\ImageData.txt";  
    string targetPath = @"D:\Apps\zDeleteme\GDI Exception\GDI Exception\ImageStorage\NiceImage.jpg";  
    string json = System.IO.File.ReadAllText(sourcePath);  
    var obj = JsonConvert.DeserializeObject<Issue>(json);  
    byte[] parms = Convert.FromBase64String(obj.ImageData);  
    using (var ms = new MemoryStream(parms))  
    {  
        using (var img = System.Drawing.Image.FromStream(ms))  
        {  
            //I tried some tips from here  
            //https://stackoverflow.com/questions/15571022/how-to-find-reason-for-generic-gdi-error-when-saving-an-image  
            System.Drawing.Image copy = img;  
            var tmpImg = new Bitmap(copy);  
            tmpImg.Save(targetPath, ImageFormat.Jpeg);  
  
        }  
    }  
}  

Thank you for any help you can offer.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,528 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
312 questions
{count} votes

5 answers

Sort by: Most helpful
  1. XuDong Peng-MSFT 10,186 Reputation points Microsoft Vendor
    2022-10-19T10:29:06.963+00:00

    Hi @moondaddy ,

    Based on your description and the code you provided, I created two test simples (console app and WebApi, tested in windows 10) to try to reproduce your issue, but unlucky I failed. They all work correctly (use the code you provided and modify some param). And you mention in your description that this issue happens intermittently, so I think I'd have to ask for more details to determine the cause of the problem or get this issue to be reproduced.

    1. When this problem occurs, does a file with the same name already exist in the corresponding path? Because when a file with the same name exists and it is occupied by another process, performing the Image.Save() method may cause such a problem.
    2. Checks if the image size exceeds 65535 pixels, and if this is the case, it will throw the relevant exception.
    3. Have you also encountered the same error in other environments? Because I see you mentioned that this problem happens in windows server 2019 and windows11. And you also need to make sure you have file write permission.

    In addition, if you can provide more detailed test info, it will help to solve the problem, such as image resources, test path and possible test steps, etc. Thank you for your understanding.

    Best regards,
    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Rijwan Ansari 746 Reputation points MVP
    2022-10-19T11:56:47.857+00:00
    0 comments No comments

  3. Lex Li (Microsoft) 5,072 Reputation points Microsoft Employee
    2022-10-19T13:15:02.047+00:00

    System.Drawing namespace is not supported in web apps by Microsoft. So, you have to use an alternative.


  4. moondaddy 911 Reputation points
    2022-10-25T00:25:27.77+00:00

    All, I have gone thru all solutions in all links above and nothing is the answer, other than system.drawing is not supported in IIS. OK. I'm very sure that saving and resizing images server side is a very common process, so..... what is the recommended way to do this using .net 4.8?

    Thank you.

    0 comments No comments

  5. Iuri Jacob 0 Reputation points
    2024-01-17T23:06:16.9+00:00

    Check if IIS user has write permission to the specified folder.

    0 comments No comments