0

我创建了 .NET Core 控制台应用程序并添加了对System.Drawing.Commonnuget 的引用。我正在尝试从ms docs运行以下代码,但它失败bitmap1.GetEncoderParameterListSystem.OverflowException

“算术运算导致溢出。”

这段代码有什么问题?我做违法的事吗?

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

堆栈跟踪:

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

更新 这个也崩溃了:

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

2 回答 2

1

编辑:似乎它在 .NET Framework 上运行良好,并且在 .NET Core 2.1 中作为 OP 抛出异常。

EDIT2:似乎这是一个已知问题,在此处列出:https ://github.com/dotnet/docs/issues/5607

于 2018-11-01T07:36:53.573 回答
1

这是 .NET Core 中的一个错误,正在为 .NET Core 5.0 解决:请参阅https://github.com/dotnet/corefx/pull/40181

于 2019-08-09T12:49:40.347 回答