madcapnmckay
madcapnmckay

Reputation: 15984

A generic error occurred in GDI+, JPEG Image to MemoryStream

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.

Upvotes: 374

Views: 620797

Answers (30)

rortegax2
rortegax2

Reputation: 517

Thanks to the other contributors who helped me locate the cause in the Stream from which the image is created. For me the best option is to get rid of the stream dependency after creating the image using Image.FromStream by making then a copy of the image using Graphics as follows:

    private static Image GetImageFromStream(Stream imageStream)
    {
        var image = Image.FromStream(imageStream);
        using var gSource = Graphics.FromImage(image);
        var bitmap = new Bitmap(image.Width, image.Height, gSource);

        using var gDest = Graphics.FromImage(bitmap);
        gDest.DrawImage(image, 0, 0);
        gDest.Save();

        return bitmap;
    }

Perhaps there's a better way in terms of performance, but this one works and I think is quite simple and easy to understand and you won't have to worry about prematurely closing the original Stream.

Upvotes: 0

Viranja kaushalya
Viranja kaushalya

Reputation: 785

This will happens when override the file, Delete the Image file and re write ,then it will resolve the issue ,

when you delete ,if you get error that file is on another process then use below codes.

 System.GC.Collect(); 
 System.GC.WaitForPendingFinalizers();
 File.Delete(FilePath);

Hope this will help you.

Upvotes: 0

Jeremy Hodge
Jeremy Hodge

Reputation: 662

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.

Upvotes: 0

Monzur
Monzur

Reputation: 1435

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.

Upvotes: 0

user7217806
user7217806

Reputation: 2104

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.

Upvotes: 0

Clinton Ward
Clinton Ward

Reputation: 2511

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

Upvotes: 0

Khalil Youssefi
Khalil Youssefi

Reputation: 414

in my case, path was wrong

just use this

String path = Server.MapPath("~/last_img.png");//Path

Upvotes: 1

Ivan Smyrnov
Ivan Smyrnov

Reputation: 339

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.

Upvotes: 0

tech-gayan
tech-gayan

Reputation: 1413

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.

Upvotes: 3

Khalil Liraqui
Khalil Liraqui

Reputation: 415

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.

Upvotes: 2

Soon Khai
Soon Khai

Reputation: 672

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.

Upvotes: 0

Hassan Rahman
Hassan Rahman

Reputation: 5203

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);

Upvotes: 5

Ihab
Ihab

Reputation: 2255

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!

Upvotes: 1

Segfault
Segfault

Reputation: 8290

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);

Upvotes: 2

Aximili
Aximili

Reputation: 29444

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;
}

Upvotes: 17

Jaimin
Jaimin

Reputation: 179

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.

Upvotes: 4

Fred
Fred

Reputation: 1312

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.

Upvotes: 66

ahsant
ahsant

Reputation: 1053

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+"

Upvotes: 20

Chris Halcrow
Chris Halcrow

Reputation: 31940

  • 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

Upvotes: 2

AltF4_
AltF4_

Reputation: 2460

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.

Upvotes: 0

Gaurang s
Gaurang s

Reputation: 832

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")

Upvotes: 6

Bruno Ferreira
Bruno Ferreira

Reputation: 89

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/)

Upvotes: 1

jeka
jeka

Reputation: 51

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);
}

Upvotes: 1

Igilima
Igilima

Reputation: 131

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.

Upvotes: 13

vipes
vipes

Reputation: 992

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.

Upvotes: 12

Andy
Andy

Reputation: 424

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.

Upvotes: 4

Klaus
Klaus

Reputation: 2590

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.

Upvotes: 0

Ε Г И І И О
Ε Г И І И О

Reputation: 12321

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.

Upvotes: 0

JAH
JAH

Reputation: 11

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.

Upvotes: 1

Amir Atashin
Amir Atashin

Reputation: 241

Save image to bitmap variable

using (var ms = new MemoryStream())
{
    Bitmap bmp = new Bitmap(imageToConvert);
    bmp.Save(ms, format);
    return ms.ToArray();
}

Upvotes: 24

Related Questions