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.


Solution 1:

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).

Solution 2:

You can use this and it will be fixed:

image.Save(stream,ImageFormat.Jpeg);