363

This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn't fit. An exception gets thrown when I save the image to the stream.

Weirdly this works perfectly with a png but gives the above error with jpg and gif which is rather confusing.

Most similar problem out there relate to saving images to files without permissions. Ironically the solution is to use a memory stream as I am doing....

public static byte[] ConvertImageToByteArray(Image imageToConvert)
{
    using (var ms = new MemoryStream())
    {
        ImageFormat format;
        switch (imageToConvert.MimeType())
        {
            case "image/png":
                format = ImageFormat.Png;
                break;
            case "image/gif":
                format = ImageFormat.Gif;
                break;
            default:
                format = ImageFormat.Jpeg;
                break;
        }

        imageToConvert.Save(ms, format);
        return ms.ToArray();
    }
}

More detail to the exception. The reason this causes so many issues is the lack of explanation :(

System.Runtime.InteropServices.ExternalException was unhandled by user code
Message="A generic error occurred in GDI+."
Source="System.Drawing"
ErrorCode=-2147467259
StackTrace:
   at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters    encoderParams)
   at System.Drawing.Image.Save(Stream stream, ImageFormat format)
   at Caldoo.Infrastructure.PhotoEditor.ConvertImageToByteArray(Image imageToConvert) in C:\Users\Ian\SVN\Caldoo\Caldoo.Coordinator\PhotoEditor.cs:line 139
   at Caldoo.Web.Controllers.PictureController.Croppable() in C:\Users\Ian\SVN\Caldoo\Caldoo.Web\Controllers\PictureController.cs:line 132
   at lambda_method(ExecutionScope , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
 InnerException: 

OK things I have tried so far.

  1. Cloning the image and working on that.
  2. Retrieving the encoder for that MIME passing that with jpeg quality setting.
Cœur
  • 37,241
  • 25
  • 195
  • 267
madcapnmckay
  • 15,782
  • 6
  • 61
  • 78

38 Answers38

222

OK I seem to have found the cause just by sheer luck and its nothing wrong with that particular method, it's further back up the call stack.

Earlier I resize the image and as part of that method I return the resized object as follows. I have inserted two calls to the above method and a direct save to a file.

// At this point the new bitmap has no MimeType
// Need to output to memory stream
using (var m = new MemoryStream())
{
       dst.Save(m, format);

       var img = Image.FromStream(m);

       //TEST
       img.Save("C:\\test.jpg");
       var bytes = PhotoEditor.ConvertImageToByteArray(img);


       return img;
 }

It appears that the memory stream that the object was created on has to be open at the time the object is saved. I am not sure why this is. Is anyone able to enlighten me and how I can get around this.

I only return from a stream because after using the resize code similar to this the destination file has an unknown mime type (img.RawFormat.Guid) and Id like the Mime type to be correct on all image objects as it makes it hard write generic handling code otherwise.

EDIT

This didn't come up in my initial search but here's the answer from Jon Skeet

Community
  • 1
  • 1
madcapnmckay
  • 15,782
  • 6
  • 61
  • 78
  • 6
    I didn't realize that when you get a bitmap from a memory stream you should not close the stream. very helpful, thank you – mcdon Sep 24 '10 at 23:04
  • 49
    Thank you. This probably saved the last of my hair. – NotMe Oct 08 '10 at 21:26
  • 7
    Thanks! this saved me a lot of time, one thing though, would you mind highlighting the cause for the error at the beginning of your answer as I (and I guess most falks) missed it on the original skim through the answers, maybe something like "DON'T CLOSE THE MEMORY STREAM IF YOU INTEND TO USE THE IMAGE AGAIN" would be great ;D – DorD Aug 27 '12 at 06:46
  • 8
    What is your "dst" variable? – WEFX May 14 '15 at 21:05
  • 1
    @madcapnmckay please explain what the 'dst' variable is and its significance – Mike T Dec 08 '15 at 02:14
  • In my case i was overwritting the image, but image file was already loaded in picturebox – sairfan May 25 '18 at 18:11
  • Maybe this works but if you open the image stream and then use the stream to resize the image as a bitmap, this error still shows. – Coded Container Nov 15 '18 at 17:49
  • 1
    It all boils down to native WinAPIs and the erratic way Microsoft has developed them. If you're interested, deep inside .NET the stream is allocated using [`CreateStreamOnHGlobal`](https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-createstreamonhglobal) function with `fDeleteOnRelease` set to `TRUE`, which causes the stream to be released/freed along with the `Image` object. It's a totally "native" issue, so I'm not sure why you guys have to deal with it in the managed code ... – ahmd0 Jul 24 '19 at 02:47
148

If you are getting that error , then I can say that your application doesn't have a write permission on some directory.

For example, if you are trying to save the Image from the memory stream to the file system , you may get that error.

Please if you are using XP, make sure to add write permission for the aspnet account on that folder.

If you are using windows server (2003,2008) or Vista, make sure that add write permission for the Network service account.

Hope it help some one.

Savindra
  • 1,481
  • 1
  • 9
  • 2
  • 9
    You didn't! I wasted 2 hours with the damn write permissions... Came here to post this. Hope you get more upvotes. :) – Gleno Jul 23 '12 at 23:22
  • 2
    THIS was the solution for me. +1 totally! – Grandizer Sep 19 '12 at 15:09
  • 5
    You can do File.WriteAllText("filename.jpg", "") then File.DeleteFile("filename.jpg") before you save the bitmap. In my benmark this only takes .001 seconds and you get a nice 'You do not have permission to save filename.jpg there' – Despertar Oct 06 '12 at 00:45
  • @Despertar You mean File.Delete(), but that is a very handy trick! Definitely going to use this whenever I save a bitmap. – Chiara Coetzee Feb 06 '15 at 15:11
  • 4
    In my case, the directory did not exist. – disappointed in SO leadership Sep 13 '15 at 20:30
  • http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream/33324011#33324011 – Gaurang s Oct 24 '15 at 22:30
  • Thank you! This noticed me I couldn't use a picture in a picturebox and edit this picture. I thought it was copied, but it used the real picture ;) – Geert Berkers Jan 06 '16 at 11:42
  • Thanks for this. I wasted a fair bit of time because of this. – MrVentzi Jan 15 '16 at 16:20
  • i changed **write permission for folder in go daddy** control panel by reading [similar](http://weblogs.asp.net/anasghanem/solving-quot-a-generic-error-occurred-in-gdi-quot-exception) post, so this works great. – Shaiju T Mar 27 '16 at 10:07
  • This was my issue as well - file permissions. But please forgive me wanting to rant a bit. The following comes from the official MS Documentation: "Do provide a rich and meaningful message text targeted at the developer when throwing an exception. The message should explain the cause of the exception and clearly describe what needs to be done to avoid the exception". https://msdn.microsoft.com/en-us/library/ms229056(v=vs.100).aspx. – Peter Jan 31 '17 at 07:21
  • FILE-IN-USE will produce the same error. For example, if you're waiting for an external program to write an image, it's possible to load the image, modify it, and try to save it before the external program releases the file lock. This answer helped me diagnose and correct this. In my case, I'm now using a temp file, and my final call to `Save` is now with a file name that did not exist in the first place. – Jonathan Nov 17 '17 at 13:02
  • In my case, VS 2019 was showing the folder to be uploaded file. However, mysteriously, the folder was not there when I try to see the folder by right clicking and 'Open folder in File Explorer'! – curious.netter Feb 13 '20 at 08:28
  • 1
    I was changing permissions, when I discovered it was a FILE-IN-USE as @Jonathan also had. The program creating the image hadn't released the lock yet. I ended up saving to a new file, instead of rewriting the original file. – astrosteve Oct 27 '20 at 19:41
64

I'll add this cause of the error as well in hopes it helps some future internet traveler. :)

GDI+ limits the maximum height of an image to 65500

We do some basic image resizing, but in resizing we try to maintain aspect ratio. We have a QA guy who's a little too good at this job; he decided to test this with a ONE pixel wide photo that was 480 pixels tall. When the image was scaled to meet our dimensions, the height was north of 68,000 pixels and our app exploded with A generic error occurred in GDI+.

You can verify this yourself with test:

  int width = 480;
  var height = UInt16.MaxValue - 36; //succeeds at 65499, 65500
  try
  {
    while(true)
    {
      var image = new Bitmap(width, height);
      using(MemoryStream ms = new MemoryStream())
      {
        //error will throw from here
        image.Save(ms, ImageFormat.Jpeg);
      }
      height += 1;
    }
  }
  catch(Exception ex)
  {
    //explodes at 65501 with "A generic error occurred in GDI+."
  }

It's too bad there's not a friendly .net ArgumentException thrown in the constructor of Bitmap.

Fred
  • 1,292
  • 10
  • 24
  • 22
    Thank you - this Internet time traveler is quite grateful for you leaving this message. – Tom West Nov 30 '11 at 17:16
  • From my testing, 65535 is actually the max value. At 65536 I start seeing the generic error. – ChaseMedallion Jan 13 '17 at 13:46
  • Just tried this again: Win10 .net 4.5 and .net 4.6.1, and it blew up at 65501 which seems even more random. Code is also fraught with syntax errors, will update :) – Fred Jan 18 '17 at 18:01
40

This article explains in detail what exactly happens: Bitmap and Image constructor dependencies

In short, for a lifetime of an Image constructed from a stream, the stream must not be destroyed.

So, instead of

using (var strm = new ... )  {
    myImage = Image.FromStream(strm);
}

try this

Stream imageStream;
...

    imageStream = new ...;
    myImage = Image.FromStream(strm);

and close imageStream at the form close or web page close.

Ivan Mesic
  • 605
  • 5
  • 8
  • Yep this one got me. I was being conscientious and wrapped my stream in a `using` and later tried to copy the image into a memory stream and received the dread "Generic error in GDI+" message. – Will Appleby Jan 01 '17 at 20:32
  • Your link was giving me infinite redirects; [this one](https://support.microsoft.com/en-us/help/814675/bitmap-and-image-constructor-dependencies) works. I was getting a problem with saving `PixelFormat.Format32bppArgb` but not `PixelFormat.Format1bppIndexed`. The article you linked explains why: GDI+ may choose to re-decode bitmap data from the source stream rather than keep everything in memory. My guess is that it doesn't re-decode 1bpp images. – labreuer Nov 03 '17 at 04:20
  • Even the new link doens't work anymore. A simple google search didn't seem to reveal the correct page. But I was very glad to find this answer! My work-around by copying to a new bitmap failed because of [this issue](https://stackoverflow.com/questions/20044431/bitmap-deep-copy-changing-pixelformat) – Katjoek Mar 01 '19 at 15:58
32

You'll also get this exception if you try to save to an invalid path or if there's a permissions issue.

If you're not 100% sure that the file path is available and permissions are correct then try writing a to a text file. This takes just a few seconds to rule out what would be a very simple fix.

var img = System.Drawing.Image.FromStream(incomingStream);

// img.Save(path);
System.IO.File.WriteAllText(path, "Testing valid path & permissions.");

And don't forget to clean up your file.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
24

Save image to bitmap variable

using (var ms = new MemoryStream())
{
    Bitmap bmp = new Bitmap(imageToConvert);
    bmp.Save(ms, format);
    return ms.ToArray();
}
harriyott
  • 10,505
  • 10
  • 64
  • 103
Amir Atashin
  • 241
  • 2
  • 2
  • This has solved my problem. Could you explain why saving the image to Bitmap scares the exception away? – jmc Apr 01 '15 at 05:53
  • Saved my day.. don't know what caused the issue but Bitmap save works.. System.Drawing.Image won't save to memory stream but Bitmap does!!! – San Apr 03 '17 at 16:33
  • This was the best solution for me. Creating new Bitmap and converting from it. – uzay95 Mar 22 '18 at 19:31
  • I know that this post is old but I wanted you to know this saved me from tearing all my hair out! lol – SlenderFuchsbau Jul 22 '20 at 20:36
18

Just in case if someone is doing as stupid stuff as I was. 1. make sure path does exist. 2. make sure you have permissions to write. 3. make sure your path is correct, in my case I was missing file name in the TargetPath :(

it should have said, your path sucks than "A generic error occurred in GDI+"

ahsant
  • 1,003
  • 4
  • 17
  • 25
17

I also got this error when saving JPEGs, but only for certain images.

My final code:

  try
  {
    img.SaveJpeg(tmpFile, quality); // This is always successful for say image1.jpg, but always throws the GDI+ exception for image2.jpg
  }
  catch (Exception ex)
  {
    // Try HU's method: Convert it to a Bitmap first
    img = new Bitmap(img); 
    img.SaveJpeg(tmpFile, quality); // This is always successful
  }

I didn't create the images so I can't tell what the difference is.
I'd appreciate if anyone could explain that.

This is my SaveJpeg function just FYI:

private static void SaveJpeg(this Image img, string filename, int quality)
{
  EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, (long)quality);
  ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
  EncoderParameters encoderParams = new EncoderParameters(1);
  encoderParams.Param[0] = qualityParam;
  img.Save(filename, jpegCodec, encoderParams);
}

private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
    var encoders = ImageCodecInfo.GetImageEncoders();
    var encoder = encoders.SingleOrDefault(c => string.Equals(c.MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase));
    if (encoder == null) throw new Exception($"Encoder not found for mime type {mimeType}");
    return encoder;
}
Diego Jancic
  • 7,280
  • 7
  • 52
  • 80
Aximili
  • 28,626
  • 56
  • 157
  • 216
13

I found that if one of the parent folders where I was saving the file had a trailing space then GDI+ would throw the generic exception.

In other words, if I tried to save to "C:\Documents and Settings\myusername\Local Settings\Temp\ABC DEF M1 Trended Values \Images\picture.png" then it threw the generic exception.

My folder name was being generated from a file name that happened to have a trailing space so it was easy to .Trim() that and move on.

Igilima
  • 131
  • 1
  • 2
13

if your code is as follows then also this error occurs

private Image GetImage(byte[] byteArray)
{
   using (var stream = new MemoryStream(byteArray))
   {
       return Image.FromStream(stream);
    }
}

The correct one is

private Image GetImage(byte[] byteArray)
{
   var stream = new MemoryStream(byteArray))
   return Image.FromStream(stream);        
}

This may be because we are returning from the using block

dhinesh
  • 4,676
  • 2
  • 26
  • 44
  • for me it was the returning in the using block. I still use using but I return the value outside of the block. thanks! – Dragouf Nov 18 '10 at 10:43
  • 1
    I found out "the hard way" that if wou're saving again that Image to a new Stream (like HttpContext.Response.OutputStream for example) you'll need to also do a stream.Flush(), if not the error occures again. – Lucian Mar 18 '11 at 14:51
12

This is an expansion / qualification of Fred's response which stated: "GDI limits the height of an image to 65534". We ran into this issue with one of our .NET applications, and having seen the post, our outsourcing team raised their hands in the air and said they couldn't fix the problem without major changes.

Based on my testing, it's possible to create / manipulate images with a height larger than 65534, but the issue arises when saving to a stream or file IN CERTAIN FORMATS. In the following code, the t.Save() method call throws our friend the generic exception when the pixel height is 65501 for me. For reasons of curiosity, I repeated the test for width, and the same limit applied to saving.

    for (int i = 65498; i <= 100000; i++)
    {
        using (Bitmap t = new Bitmap(800, i))
        using (Graphics gBmp = Graphics.FromImage(t))
        {
            Color green = Color.FromArgb(0x40, 0, 0xff, 0);
            using (Brush greenBrush = new SolidBrush(green))
            {
                // draw a green rectangle to the bitmap in memory
                gBmp.FillRectangle(greenBrush, 0, 0, 799, i);
                if (File.Exists("c:\\temp\\i.jpg"))
                {
                    File.Delete("c:\\temp\\i.jpg");
                }
                t.Save("c:\\temp\\i.jpg", ImageFormat.Jpeg);
            }
        }
        GC.Collect();
    }

The same error also occurs if you write to a memory stream.

To get round it, you can repeat the above code and substitute ImageFormat.Tiff or ImageFormat.Bmp for ImageFormat.Jpeg.

This runs up to heights / widths of 100,000 for me - I didn't test the limits. As it happens .Tiff was a viable option for us.

BE WARNED

The in memory TIFF streams / files consume more memory than their JPG counterparts.

vipes
  • 922
  • 1
  • 9
  • 17
12

Had a very similar problem and also tried cloning the image which doesn't work. I found that the best solution was to create a new Bitmap object from the image that was loaded from the memory stream. That way the stream can be disposed of e.g.

using (var m = new MemoryStream())
{
    var img = new Bitmap(Image.FromStream(m));
    return img;
}

Hope this helps.

Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
HU.
  • 121
  • 1
  • 2
6

Error occurring because of Permission. make sure folder have ALL THE PERMISSION.

public Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0,
          imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }

 img.Save("YOUR PATH TO SAVE IMAGE")
Gaurang s
  • 831
  • 6
  • 18
5

SOLVED - I had this exact problem. The fix, for me, was to up the disk quota for IUSR on the IIS server. In this instance, we have a catalog app with images of items and such. The upload quota for the "Anonymous Web User" was set to 100MB, which is the default for this particular hosting company's IIS servers. I upped it to 400MB and was able to upload images without error.

This might not be your issue, but if it is, it's an easy fix.

user229044
  • 232,980
  • 40
  • 330
  • 338
Marco
  • 51
  • 1
  • 1
5

Simple, create a new instance of Bitmap solves the problem.

string imagePath = Path.Combine(Environment.CurrentDirectory, $"Bhatti{i}.png");
Bitmap bitmap = new Bitmap(image);
bitmap.Save(imagePath);
Hassan Rahman
  • 4,953
  • 1
  • 34
  • 32
5

In my case the problem was in the path I was saving (the root C:\). Changing it to D:\111\ made the exception go away.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Ani
  • 2,636
  • 1
  • 21
  • 17
4

Another cause for this error - the path you indicate in the Save method of the Bitmap instance doesn't exist or you haven't supplied a full / valid path.

Just had this error because I was passing in a filename and not a full path!

It happens!

MytyMyky
  • 608
  • 7
  • 15
4

My turn!

using (System.Drawing.Image img = Bitmap.FromFile(fileName))
{
      ... do some manipulation of img ...
      img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}

Got it on the .Save... because the using() is holding the file open, so I can't overwrite it. Maybe this will help someone in the future.

Andy
  • 414
  • 4
  • 8
4

Same problem I was facing. But in my case, I was trying to save file in C drive and it was not accessible. So I tried it to save in D drive which was fully accessible and I succeeded.

So first check your folders in which you are trying to save. You must have all (read and write) rights for that particular folder.

Jaimin
  • 171
  • 1
  • 1
  • 11
2

Just to throw another possible solution on the pile, I'll mention the case I ran into with this error message. The method Bitmap.Save would throw this exception when saving an bitmap I had transformed and was displaying. I discovered it would not throw the exception if the statement had a breakpoint on it, nor would it if the Bitmap.Save was preceeded by Thread.Sleep(500) so I suppose there is some sort of resource contention going on.

Simply copying the image to a new Bitmap object was enough to prevent this exception from appearing:

new Bitmap(oldbitmap).Save(filename);
Segfault
  • 8,036
  • 3
  • 35
  • 54
2

I notice that your "jpeg" case is actually:

            default:
                format = ImageFormat.Jpeg;
                break;

Are you sure that the format is jpeg and not something else?

I'd try:

            case "image/jpg": // or "image/jpeg" !
                format = ImageFormat.Jpeg;
                break;

Or check what imageToConvert.MimeType() is actually returning.

UPDATE

Is there any other initialisation you need to do to the MemoryStream object?

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • Thanks. It is definitely being called with the correct format. I load a jpg, debug and confirm the mime is recognised as image/jpeg and the format is JPG. – madcapnmckay Jun 27 '09 at 15:58
  • 3
    Oh well - I always try to eliminate the obvious first. I can't count the number of times I've not done that and it's come back to bite me later. – ChrisF Jun 27 '09 at 16:02
2
  • I had this issue on a test server but not on the live server.
  • I was writing the image to a stream, so it wasn't a permission issue.
  • I'd been directly deploying some of the .dll's to the test server.
  • Deploying the entire solution fixed the issue, so it was probably a weird compilation mismatch
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
2

We had a similar problem on generating a PDF or resize image using ImageProcessor lib on production server.

Recycle the application pool fix the issue.

DreamTeK
  • 32,537
  • 27
  • 112
  • 171
tech-gayan
  • 1,373
  • 1
  • 10
  • 25
2

One other cause of this error and that solve my problème is that your application doesn't have a write permission on some directory.

so to complete the answer of savindra : https://stackoverflow.com/a/7426516/6444829.

Here is how you Grant File Access to IIS_IUSERS

To provide access to an ASP.NET application, you must grant access to the IIs_IUSERS.

To grant read, write, and modify permissions to a specific File or Folder

  1. In Windows Explorer, locate and select the required file.

  2. Right click the file, and then click Properties.

  3. In the Properties dialog box, click the Security tab.

  4. On the Security tab, examine the list of users. (If your application is running as a Network Service, add the network service account in the list and grant it the permission.

  5. In the Properties dialog box, click IIs_IUSERS, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.

  6. Click Apply, and then click OK.

this worked for me in my IIS of windows server 2016 and local IIS windows 10.

Khalil Liraqui
  • 385
  • 1
  • 5
  • 21
1

If you are trying to save an image to a remote location be sure to add the NETWORK_SERVICE user account into the security settings and give that user read and write permissions. Otherwise it is not going to work.

Bartek
  • 1,059
  • 6
  • 18
JAH
  • 11
  • 1
1
byte[] bts = (byte[])page1.EnhMetaFileBits; 
using (var ms = new MemoryStream(bts)) 
{ 
    var image = System.Drawing.Image.FromStream(ms); 
    System.Drawing.Image img = image.GetThumbnailImage(200, 260, null, IntPtr.Zero);      
    img.Save(NewPath, System.Drawing.Imaging.ImageFormat.Png);
}
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
jeka
  • 51
  • 1
1

I also get this error because i'm trying to save images with the same name of previous saved images.

Make sure that you don't save images with duplicate name.

Use for thar for example a 'Random' function (How does C#'s random number generator work?) or for example generate a Guid (http://betterexplained.com/articles/the-quick-guide-to-guids/)

Community
  • 1
  • 1
1

Possible problems that cause such an error are:

  1. Directory does not exist (The method you are calling will not automatically create this directory for you)
  2. The security permissions to write to the output directory do not allow the user running the app to write

I hope this helps, this was the fix for my issue, I simply made sure that the output directory exists before saving the output image!

Ihab
  • 2,225
  • 1
  • 20
  • 32
1

in my case, path was wrong

just use this

String path = Server.MapPath("~/last_img.png");//Path
Khalil Youssefi
  • 385
  • 6
  • 10
0

For me I was using the Image.Save(Stream, ImageCodecInfo, EncoderParameters) and apparently this was causing the infamous A generic error occurred in GDI+ error.

I was trying to use EncoderParameter to save the jpegs in 100% quality. This was working perfectly on "my machine" (doh!) and not on production.

When I used the Image.Save(Stream, ImageFormat) instead, the error disappeared! So like an idiot I continued to use the latter although it saves them in default quality which I assume is just 50%.

Hope this info helps someone.

Ε Г И І И О
  • 11,199
  • 1
  • 48
  • 63
0

I encountered the problem too. The problem was due to the loading stream being disposed. But I did not dispose it, it was inside .Net framework. All I had to do was use:

image_instance = Image.FromFile(file_name);

instead of

image_instance.Load(file_name);

image_instance is of type System.Windows.Forms.PictureBox! PictureBox's Load() disposes the stream which the image was loaded from, and I did not know that.

Klaus
  • 2,460
  • 1
  • 21
  • 23
0

Based on the answer from @savindra , if you RHM on your application and try and run as an administrator then it should resolve your problem.

Mine seemed to be a permission issue.

AltF4_
  • 2,312
  • 5
  • 36
  • 56
0

My console app got the same error message: "A generic error occurred in GDI+." The error happened in line newImage.Save as refer to the following code.

for (int i = 1; i <= 1000; i++)
{
   Image newImage = Image.FromFile(@"Sample.tif");
   //...some logic here
   newImage.Save(i + ".tif", , ImageFormat.Tiff);
}

The program returned error when the RAM usage is around 4GB, and managed to solve it by changed the Program Target to x64 in project properties.

Soon Khai
  • 652
  • 6
  • 13
0

I have strange solution for this problem. I was fased to this during coding. I thought that Bitmap is struct and wrap around it with method. In my imagination Bitmap will be copies inside method and returned out of method. But later I checked that it's class, and i have no idea why is it helped me, but it Works! Maybe someone have time and have fun to look at IL code of this ;) Not sure maybe it's working cause this method is static inside static method, I don't know.

        public SomeClass
        {
            public byte[] _screenShotByte;
            public Bitmap _screenShotByte;
            public Bitmap ScreenShot 
            { 
                get
                {
                    if (_screenShot == null)
                    {
                        _screenShotByte = ScreenShot();
                        using (var ms = new MemoryStream(_screenShotByte))
                        {
                            _screenShot = (Bitmap)Image.FromStream(ms);
                        }
                         
                        ImageUtils.GetBitmap(_screenShot).Save(Path.Combine(AppDomain.CurrentDomain.BaseDirectory) ,$"{DateTime.Now.ToFileTimeUtc()}.png"));
            
                    }
                    return ImageUtils.GetBitmap(_screenShot);
                }
            }
            public byte[] ScreenShot()
            {
                ///....return byte array for image in my case implementedd like selenium screen shot 
            }
        }
        public static ImageUtils
        {
            public static Bitmap GetBitmap(Bitmap image)
            {
                return Bitmap;
            }
        }


p.s. It's not trolling this solution solved problem of keep using bitmap after saving in another places.

Ivan Smyrnov
  • 339
  • 2
  • 10
0

If you have come this far this is something else you can try..

Change your application pool identity setting from ApplicationPoolIdentity to LocalSystem to verify its a permission problem.

However, don't use this setting long-term as it's a security risk; use it only as a diagnosis

Clinton Ward
  • 2,441
  • 1
  • 22
  • 26
0

When using NTFS, this also might happen if there are too many files (beyond a million as also reported here) in the target directory. See this answer for further details.

user7217806
  • 2,014
  • 2
  • 10
  • 12
0

if your code needs (write) access to some files or folders and make sure the file or folder exists and that you have permission to write.

My problem solved by giving Folder access to the users.

Monzur
  • 1,341
  • 14
  • 11
0

In my case, I was attempting to save the file as the form was closing, but there was a picture box on the form that still had the image loaded, which had a lock on the file. I called pictureBox.Dispose(); before Image.Save() and the issue was resolved.

Jeremy Hodge
  • 612
  • 3
  • 14