![](/img/trans.png)
[英]Image.Save crashing: {“Value cannot be null.\r\nParameter name: encoder”}
[英]Image.Save() throws exception "Value cannot be null./r/nParameter name: encoder"
使用 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());
}
}
}
RawFormat 在現有的 ImageEncoders 列表中不存在,因為下面的代碼返回 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 崩潰:{“值不能為空。\\r\\n參數名稱:編碼器”} 為什么 Image.Save(Stream, ImageFormat) 會拋出異常?
歡迎任何建議。
如果從磁盤加載圖像,則可以使用image.RawFormat
以原始格式保存該圖像。 但是,沒有與內存中位圖(這是您在此示例應用程序中創建的)相關聯的編碼器,因此您必須自己指定圖像格式(即ImageFormat.Bmp
)。
您可以使用它,它將被修復:
image.Save(stream,ImageFormat.Jpeg);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.