【问题标题】:How to validate image file format in C#如何在 C# 中验证图像文件格式
【发布时间】:2011-01-04 10:48:04
【问题描述】:

有谁知道验证给定图像的文件格式的脚本。目前我正在填充一个图像对象,查看它的高度、宽度和分辨率。我没有看到此对象的任何特定属性可以解释文件格式。

我想检查 jpg、AI、PSD、High Jes Jpg、Bitmap 和 Tiff。

这是我当前的脚本:

        protected bool IsValidImage(HttpPostedFileBase file, string fileName) {

        //verify that the image is no more than 648 wide and 648 pixels tall
        Image imgPhoto = Image.FromStream(file.InputStream);
        if (imgPhoto.Width > 648)
            return false;
        if (imgPhoto.Height > 648)
            return false;
        if (imgPhoto.HorizontalResolution != 72 || imgPhoto.VerticalResolution != 72)
            return false;
        return true;

    }

提前致谢

【问题讨论】:

  • 好吧,如果你有文件名,为什么不检查扩展名?
  • Image 类将无法处理 AI 或 PSD...
  • @Thomas - 我相信如果您安装了 AI 或 PSD 编解码器,那么 Image 将能够使用 ImageFormat GUID 告诉您。

标签: c# graphics image


【解决方案1】:

您可以访问Wotsit 以找出在文件开头用作标记的魔术字节。点击“图形文件”查看文件格式列表。

【讨论】:

  • CodeKaizen 的回答非常好...+1 来自我...不知道...谢谢! :)
  • 链接不再有效。因此,答案毫无价值:-/
【解决方案2】:

使用Image.RawFormat。结果是ImageFormat 类的一个实例,可以与ImageFormat 的静态属性进行比较。

更多详情请见the ImageFormat class properties

【讨论】:

  • 如何从 ImageFormat GUID 中判断图像类型是 PSD 还是 AI?
  • 顺便说一句,谢谢你的回答。它是正确的。只需要测试 PSD 和 AI 格式。
  • @Billy - 您是否考虑过使用 Windows 映像组件 (WIC)。我更肯定的是,在这种情况下,您可以使用编解码器来解码文件格式,而且 WIC 对服务器友好,而 GDI 则不是。
  • 不,首先我对 GDI 或成像对象不是很熟悉。不必过多地与他们打交道。不过会检查一下。感谢您的快速回复。
【解决方案3】:
public bool validateImage(byte[] bytes)
{
  try 
{
 Stream stream = new MemoryStream(bytes);
 using(Image img = Image.FromStream(stream))
 {
   if (img.RawFormat.Equals(ImageFormat.Bmp) ||
       img.RawFormat.Equals(ImageFormat.Gif) ||
       img.RawFormat.Equals(ImageFormat.Jpeg) ||
       img.RawFormat.Equals(ImageFormat.Png))
     return true;
 }
 return false;
} 
catch
{
 return false;
}

}

【讨论】:

    【解决方案4】:

    怎么样:

    bool isJpeg = imgPhoto.RawFormat.Equals(Imaging.ImageFormat.Jpeg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-17
      • 2011-01-26
      • 2010-10-03
      • 2013-04-04
      • 2012-05-10
      • 2018-05-30
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多