代码之家  ›  专栏  ›  技术社区  ›  David4866

如何在C#[重复]中检查“是否有效图像文件”

  •  1
  • David4866  · 技术社区  · 8 年前

    我试着不使用 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();
            }
        }
    }
    

    但如果测试。jpg是损坏的,那么C#将显示错误,所以我的问题是:有这样的函数吗 IsValidImage() 在C#?

    谢谢!

    1 回复  |  直到 8 年前
        1
  •  2
  •   James.YinG    8 年前

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

        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
    }