我创建了 .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;
}
}
堆栈跟踪:
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);