Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# “如何检查”;是否为有效的图像文件;在C中#_C#_Bitmap - Fatal编程技术网

C# “如何检查”;是否为有效的图像文件;在C中#

C# “如何检查”;是否为有效的图像文件;在C中#,c#,bitmap,C#,Bitmap,我试着不使用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) {

我试着不使用
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()的函数


谢谢

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

    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
}
公共静态ImageType检查ImageType(字符串路径)
{
字节[]buf=新字节[2];
尝试
{
使用(StreamReader sr=新StreamReader(路径))
{
int i=sr.BaseStream.Read(buf,0,buf.Length);
如果(i!=基本长度)
{
返回ImageType.None;
}
}
}
捕获(异常exc)
{
//Debug.Print(exc.ToString());
返回ImageType.None;
}
返回CheckImageType(buf);
}
公共静态ImageType检查ImageType(字节[]buf)
{
if(buf==null | | buf.Length<2)
{
返回ImageType.None;
}

int key=(buf[1]希望这可能有助于复制&这个问题不是重复的,因为它是关于内存中位图的构造。它不是关于从文件加载的位图,并且需要验证测试。thx很多,但是_imageTag没有定义,为什么呢?它是一个映射,int到图像类型,比如:它是一个字典,int到图像类型,比如:_imageType[(int)ImageType.JPG]=ImageType.JPG