我创建了.NET Core控制台应用程序,并添加了对System.Drawing.Common
nuget的引用。
我正在尝试从ms docs运行以下代码,但是在bitmap1.GetEncoderParameterList
和System.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;
}
}
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
更新 这个也会崩溃:
Bitmap bitmap1 = new Bitmap(Image.FromFile(@"C:\temp\0\2.png"));
ImageCodecInfo pngEncoder = GetEncoder(ImageFormat.Png);
答案 0 :(得分:1)
编辑:似乎它在.NET Framework上运行良好,并且作为带有.NET Core 2.1的OP抛出异常。
EDIT2:似乎是一个已知问题,在此处列出:https://github.com/dotnet/docs/issues/5607
答案 1 :(得分:1)
这是.NET Core中的错误,正在针对.NET Core 5.0解决:请参见https://github.com/dotnet/corefx/pull/40181。