Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ImageFormat from System.Drawing.Image.RawFormat

This code fails when trying to call Image.Save(MemoryStream, ImageFormat).

I get the exception:

a Value cannot be null.Parameter name: encoder"

ImageFormat format = generatedImage.RawFormat as ImageFormat;
image.ImageData = generatedImage.Save(format);

It works if I pass in an ImageFormat object directly e.g. ImageFormat.Jpeg.

What is the best way of converting the rawformat to ImageFormat (ideally without a switch statement or lots of if statements)

Thanks Ben

like image 682
Ben Foster Avatar asked Nov 26 '10 15:11

Ben Foster


2 Answers

I'm sorry, I found no possibility to directly extract a "proper" ImageFormat from the parsed or generated Image object.

This is my code, you can adopt it by storing the static ImageFormat member instead of the mimetype.

                if (image.RawFormat.Equals(ImageFormat.Jpeg))
                    binary.MetaInfo.Mimetype = "image/jpeg";
                else if (image.RawFormat.Equals(ImageFormat.Bmp))
                    binary.MetaInfo.Mimetype = "image/bmp";
                else if (image.RawFormat.Equals(ImageFormat.Emf))
                    binary.MetaInfo.Mimetype = "image/emf";
                else if (image.RawFormat.Equals(ImageFormat.Exif))
                    binary.MetaInfo.Mimetype = "image/exif";
                else if (image.RawFormat.Equals(ImageFormat.Gif))
                    binary.MetaInfo.Mimetype = "image/gif";
                else if (image.RawFormat.Equals(ImageFormat.Icon))
                    binary.MetaInfo.Mimetype = "image/icon";
                else if (image.RawFormat.Equals(ImageFormat.Png))
                    binary.MetaInfo.Mimetype = "image/png";
                else if (image.RawFormat.Equals(ImageFormat.Tiff))
                    binary.MetaInfo.Mimetype = "image/tiff";
                else if (image.RawFormat.Equals(ImageFormat.Wmf))
                    binary.MetaInfo.Mimetype = "image/wmf";

You could tidy it up by using an array of static ImageFormat members, but I think you won't be able to avoid a switch or a loop.

Best regards, Matthias

like image 101
Matthias Wuttke Avatar answered Sep 24 '22 13:09

Matthias Wuttke


are you looking for this?


System.Drawing.Imaging.ImageFormat fmt = new System.Drawing.Imaging.ImageFormat(generatedImage.RawFormat.Guid);
like image 29
Cesare Imperiali Avatar answered Sep 25 '22 13:09

Cesare Imperiali