System.OverflowException: 'Arithmetic operation resulted in an overflow.'

5.4k Views Asked by At

I created .NET Core console app and added reference to System.Drawing.Common nuget. I'm trying to run the following code from ms docs, but it fails on bitmap1.GetEncoderParameterList with System.OverflowException:

'Arithmetic operation resulted in an overflow.'

What is wrong with this code? Do I make something illegal?

class Program
{

   public static void Main(string[] args)
   {
      new Program().GetSupportedParameters();
   }
   private void GetSupportedParameters()
   {
       Bitmap bitmap1 = new Bitmap(1, 1);
       ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
       //this one also does not work:
       //Bitmap bitmap1 = new Bitmap(Image.FromFile(@"C:\temp\0\2.png"));
       //ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Png);
       EncoderParameters paramList = bitmap1.GetEncoderParameterList(jpgEncoder.Clsid);
       EncoderParameter[] encParams = paramList.Param;
       StringBuilder paramInfo = new StringBuilder();

       for (int i = 0; i < encParams.Length; i++)
       {
           paramInfo.Append("Param " + i + " holds " + encParams[i].NumberOfValues +
                    " items of type " +
                encParams[i].ValueType + "\r\n" + "Guid category: " + encParams[i].Encoder.Guid + "\r\n");

       }            
   }

   private ImageCodecInfo GetEncoder(ImageFormat format)
   {
       ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

       foreach (ImageCodecInfo codec in codecs)
       {
          if (codec.FormatID == format.Guid)
          {
               return codec;
          }
       }
       return null;
    }
 }

StackTrace:

at System.Drawing.Imaging.EncoderParameters.ConvertFromMemory(IntPtr memory)
at System.Drawing.Image.GetEncoderParameterList(Guid encoder)
at ConsoleApp16.Program.GetSupportedParameters() in Program.cs:line 19
at ConsoleApp16.Program.Main(String[] args)
in Program.cs:line 13

UPDATE This one also crashes:

Bitmap bitmap1 = new Bitmap(Image.FromFile(@"C:\temp\0\2.png"));
ImageCodecInfo pngEncoder = GetEncoder(ImageFormat.Png);
2

There are 2 best solutions below

4
On

EDIT: Seems like it's working fine on .NET Framework and it throws an exception as OP with .NET Core 2.1.

EDIT2: Seems like it's a known issue, listed here: https://github.com/dotnet/docs/issues/5607

0
On

This is a bug in .NET Core and is being addressed for .NET Core 5.0: see https://github.com/dotnet/corefx/pull/40181.