【问题标题】:How to check "Is Valid Image File" in C# [duplicate]如何在 C# 中检查“是有效的图像文件”[重复]
【发布时间】:2018-05-04 09:01:32
【问题描述】:

我正在尝试不使用try-catch 来实现这个目标

这是我的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Bitmap imagePattern = new Bitmap(@"test.jpg");
            Console.Read();
        }
    }
}

但如果 test.jpg 损坏,那么 C# 会显示错误,所以我的问题是:C# 中是否有类似 IsValidImage() 的函数?

谢谢!

【问题讨论】:

标签: c# bitmap


【解决方案1】:

我想你可以检查一下文件头。

    public static ImageType CheckImageType(string path)
    {
        byte[] buf = new byte[2];
        try
        {
            using (StreamReader sr = new StreamReader(path))
            {
                int i = sr.BaseStream.Read(buf, 0, buf.Length);
                if (i != buf.Length)
                {
                    return ImageType.None;
                }
            }
        }
        catch (Exception exc)
        {
            //Debug.Print(exc.ToString());
            return ImageType.None;
        }
        return CheckImageType(buf);
    }

    public static ImageType CheckImageType(byte[] buf)
    {
        if (buf == null || buf.Length < 2)
        {
            return ImageType.None;
        }

        int key = (buf[1] << 8) + buf[0];
        ImageType s;  
        if (_imageTag.TryGetValue(key, out s))
        {
            return s;
        }  
        return ImageType.None;
    }

public enum ImageType
{
    None = 0,
    BMP = 0x4D42,
    JPG = 0xD8FF,
    GIF = 0x4947,
    PCX = 0x050A,
    PNG = 0x5089,
    PSD = 0x4238,
    RAS = 0xA659,
    SGI = 0xDA01,
    TIFF = 0x4949
}

【讨论】:

  • thx 很多,但 _imageTag 没有定义,这是为什么呢?
  • 这是一个映射,int到图像类型,如:
  • 它是一个字典,int为图像类型,如:_imageType[(int)ImageType.JPG] = ImageType.JPG
猜你喜欢
  • 2010-10-27
  • 2014-11-15
  • 2013-08-15
  • 2011-10-04
  • 2017-05-02
  • 1970-01-01
  • 2020-12-04
相关资源
最近更新 更多