简体   繁体   中英

Image.Save() throws exception "Value cannot be null./r/nParameter name: encoder"

I am getting "Value cannot be null.\\r\\nParameter name: encoder" error while saving a Bitmap image using RawFormat. Sample code:

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

The RawFormat doesn't exist in the existing list of ImageEncoders as below code returns null.

var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid);

Note: The image could be any type(JPEG, BMP, PNG) etc. Image.Save() should work on image.RawFormat. RawFormat is not Bitmap type. If I Change image.RawFormat to ImageFormat.Bmp, the save operation succeeds.

Referred below links but found nothing for making it independent of image type.

Image.Save crashing: {"Value cannot be null.\\r\\nParameter name: encoder"} Why is Image.Save(Stream, ImageFormat) throwing an exception?

Any suggestions are welcome.

If you load an image from disk, you can use image.RawFormat to save that image using its original format. However there is no encoder associated with an in-memory bitmap (which is what you are creating in this sample application), so you'll have to specify an image format yourself (ie. ImageFormat.Bmp ).

您可以使用它,它将被修复:

image.Save(stream,ImageFormat.Jpeg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM