Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

image

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.

like image 754
Praveen Raghuvanshi Avatar asked Aug 11 '14 11:08

Praveen Raghuvanshi


2 Answers

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

like image 132
C.Evenhuis Avatar answered Oct 15 '22 19:10

C.Evenhuis


You can use this and it will be fixed:

image.Save(stream,ImageFormat.Jpeg);
like image 15
Eric Avatar answered Oct 15 '22 19:10

Eric