从 System.Drawing.Image.RawFormat 获取 ImageFormat

发布于 2024-10-04 18:20:42 字数 509 浏览 8 评论 0原文

此代码在尝试调用 Image.Save(MemoryStream, ImageFormat) 时失败。

我得到例外:

值不能为空。参数名称:编码器”

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

如果我直接传入 ImageFormat 对象,例如 ImageFormat.Jpeg,它就可以工作。

转换 的最佳方法是什么>rawformatImageFormat (最好没有 switch 语句或大量 if 语句)

谢谢 本

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

蓝眼泪 2024-10-11 18:20:43

我使用以下 hepler 方法来实现相同的目的:

public static string GetMimeType(Image i)
{
    var imgguid = i.RawFormat.Guid;
    foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders()) 
    {
        if (codec.FormatID == imgguid)
            return codec.MimeType;
    }
    return "image/unknown";
}

I use following hepler method for the same:

public static string GetMimeType(Image i)
{
    var imgguid = i.RawFormat.Guid;
    foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders()) 
    {
        if (codec.FormatID == imgguid)
            return codec.MimeType;
    }
    return "image/unknown";
}
夜雨飘雪 2024-10-11 18:20:43

抱歉,我发现无法直接从解析或生成的 Image 对象中提取“正确的” ImageFormat 。

这是我的代码,您可以通过存储静态 ImageFormat 成员而不是 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";

您可以通过使用静态 ImageFormat 成员数组来整理它,但我认为您将无法避免切换或循环。

最好的问候,马蒂亚斯

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

司马昭之心 2024-10-11 18:20:43

你在找这个吗?


System.Drawing.Imaging.ImageFormat fmt = new System.Drawing.Imaging.ImageFormat(generatedImage.RawFormat.Guid);

are you looking for this?


System.Drawing.Imaging.ImageFormat fmt = new System.Drawing.Imaging.ImageFormat(generatedImage.RawFormat.Guid);
吻风 2024-10-11 18:20:43

还有一种方法可以将 ImageRawFormat 格式保存到某个 Stream 中。请参阅 http:// bytes.com/topic/c-sharp/answers/944402-how-access-raw-image-data-resource-file#post3733044

对于我来说,其工作原理如下:

byte[] GetRawImageData(Image img)
{
    using(MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, img.RawFormat);
        return ms.ToArray();
    }
}

There's also a way to save an Image in its RawFormat to some Stream. See http://bytes.com/topic/c-sharp/answers/944402-how-access-raw-image-data-resource-file#post3733044

For me that works like the following:

byte[] GetRawImageData(Image img)
{
    using(MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, img.RawFormat);
        return ms.ToArray();
    }
}
夏日落 2024-10-11 18:20:43

Cesare Imperiali 的上述答案在我的测试中有效。唯一的缺点(如果重要的话)是 Jpeg 的 .ToString() 返回“[ImageFormat: b96b3cae-0728-11d3-9d7b-0000f81ef32e]”而不是“Jpeg”。

如果这对您很重要,那么您可以使用更少的代码获得精确的静态 ImageFormat 的一种方法是:

public static class ImageFilesHelper
{
    public static List<ImageFormat> ImageFormats =>
        typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public)
          .Select(p => (ImageFormat)p.GetValue(null, null)).ToList();

    public static ImageFormat ImageFormatFromRawFormat(ImageFormat raw) =>
        ImageFormats.FirstOrDefault(f => raw.Equals(f)) ?? ImageFormat.Bmp;

}
// Usage:
var format = ImageFilesHelper.ImageFormatFromRawFormat(Image.FromFile(myFile).RawFormat);

Cesare Imperiali's answer above worked in my tests. The only downside (if it matters) is that the .ToString() for a Jpeg returns "[ImageFormat: b96b3cae-0728-11d3-9d7b-0000f81ef32e]" instead of "Jpeg".

If that matters to you, one way you can get the precise static ImageFormat's with less code is this way:

public static class ImageFilesHelper
{
    public static List<ImageFormat> ImageFormats =>
        typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public)
          .Select(p => (ImageFormat)p.GetValue(null, null)).ToList();

    public static ImageFormat ImageFormatFromRawFormat(ImageFormat raw) =>
        ImageFormats.FirstOrDefault(f => raw.Equals(f)) ?? ImageFormat.Bmp;

}
// Usage:
var format = ImageFilesHelper.ImageFormatFromRawFormat(Image.FromFile(myFile).RawFormat);
影子是时光的心 2024-10-11 18:20:43

Cheburek 答案的 VB.NET 翻译:

Private Function GetMimeType(i As Drawing.Image) As String
    Dim imgguid As Guid = i.RawFormat.Guid
    For Each codec As ImageCodecInfo In ImageCodecInfo.GetImageDecoders()
        If (codec.FormatID = imgguid) Then
            Return codec.MimeType
        End If
    Next
    Return "image/unknown"
End Function

The VB.NET translation of Cheburek's answer:

Private Function GetMimeType(i As Drawing.Image) As String
    Dim imgguid As Guid = i.RawFormat.Guid
    For Each codec As ImageCodecInfo In ImageCodecInfo.GetImageDecoders()
        If (codec.FormatID = imgguid) Then
            Return codec.MimeType
        End If
    Next
    Return "image/unknown"
End Function
泼猴你往哪里跑 2024-10-11 18:20:43

我尝试了比较指南的 Cheburek 方法。但对于某些 png 图像,指南不匹配。所以我必须编写一个逻辑,它将使用 Matthias Wuttke 的解决方案和 Cheburek 的解决方案提到的方法。

首先,我检查了 ImageCodecinfo,如果代码找不到图像格式,那么我使用 Matthias Wuttke 的解决方案比较图像格式。

如果上述两种解决方案都失败,则使用扩展方法来获取文件 mime 类型。

如果 mime 类型发生变化,则文件也会发生变化,我们正在计算下载的文件校验和,以与服务器上原始文件的校验和相匹配..所以对我们来说,获得正确的文件作为输出非常重要。

I tried Cheburek method of comparing the guid. but for some of the png images the guids were not matching. so i had to write a logic which will use both the methods mentioned by Matthias Wuttke's solution and Cheburek's solution.

first i was checking with the ImageCodecinfo and if code does not find the imageformat then i compared the imageformat using Matthias Wuttke's solution.

if both the above mentioned solution failed then used the extension method to get the file mime type..

if the mime type changes then the file also changes, we were calculating the downloaded files checksum to match with the checksum of the original file on the server .. so for us it was importent to get proper file as output.

趁年轻赶紧闹 2024-10-11 18:20:43

从 RawFormat 中查找图像扩展名并保存的新鲜、现代且通用的答案如下:

var formatDescription = ImageCodecInfo.GetImageDecoders().FirstOrDefault(w => w.FormatID == image.RawFormat.Guid)?.FormatDescription;

filePath = Path.ChangeExtension(filePath, formatDescription);

image.Save(filePath);

A fresh, modern and general answer for finding an image extension from RawFormat and saving is like this:

var formatDescription = ImageCodecInfo.GetImageDecoders().FirstOrDefault(w => w.FormatID == image.RawFormat.Guid)?.FormatDescription;

filePath = Path.ChangeExtension(filePath, formatDescription);

image.Save(filePath);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文