How to get contentType from System.Drawing.Imaging.ImageFormat

后端 未结 2 1138
遥遥无期
遥遥无期 2021-02-20 03:39

If I have Bitmap and it has RawFormat property.

How can I get Content Type from this ImageFormat object?

Bitmap image = new Bitmap(stream);
ImageFormat i         


        
相关标签:
2条回答
  • 2021-02-20 03:46

    I believe I've come up with a simple solution that works great for images. This uses extension methods and Linq, so it will work on .net framework 3.5+. Here's the code and unit test:

    public static string GetMimeType(this Image image)
    {
        return image.RawFormat.GetMimeType();
    }
    
    public static string GetMimeType(this ImageFormat imageFormat)
    {
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType;
    }
    
    [TestMethod]
    public void can_get_correct_mime_type()
    {
        Assert.AreEqual("image/jpeg", ImageFormat.Jpeg.GetMimeType());
        Assert.AreEqual("image/gif", ImageFormat.Gif.GetMimeType());
        Assert.AreEqual("image/png", ImageFormat.Png.GetMimeType());
    }
    
    0 讨论(0)
  • 2021-02-20 04:01

    If you want to determine the MIME type from a file name (or extension), here is a link that uses the registry: Get MimeType from a File Name

    0 讨论(0)
提交回复
热议问题