使用 RawFormat 保存位图图像时,出现“值不能为空。\r\n参数名称:编码器”错误。 示例代码:
class Program
{
static void Main(string[] args)
{
try
{
var image = new System.Drawing.Bitmap(500, 400);
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
}
catch (Exception exp)
{
Console.WriteLine(exp.ToString());
}
}
}
现有的 ImageEncoder 列表中不存在 RawFormat,因为下面的代码返回 null。
var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid);
注意:图像可以是任何类型(JPEG、BMP、PNG)等。Image.Save() 应该适用于 image.RawFormat。 RawFormat 不是位图类型。如果我将 image.RawFormat 更改为 ImageFormat.Bmp,则保存操作成功。
引用了下面的链接,但没有找到任何可以使其独立于图像类型的内容。
Image.Save crashing: {"Value cannot be null.\r\nParameter name: encoder"} Why is Image.Save(Stream, ImageFormat) throwing an exception?
欢迎任何建议。
最佳答案
如果从磁盘加载图像,则可以使用image.RawFormat
使用其原始格式保存该图像。但是,没有与内存中位图关联的编码器(这是您在此示例应用程序中创建的),因此您必须自己指定图像格式(即 ImageFormat.Bmp
) .
关于c# - Image.Save() 抛出异常 "Value cannot be null./r/nParameter name: encoder",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46765931/