1

I'm trying not using try-catch to achieve this goal

here's my code

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();
        }
    }
}

But if test.jpg is damage then C# will show error, so my question: is there a function like IsValidImage() in C#?

THX!

David4866
  • 43
  • 7
  • Hope this might help https://stackoverflow.com/a/210667/3583859 – Vijay Kumbhoje Nov 21 '17 at 01:49
  • Duplicate of https://stackoverflow.com/questions/8349693/how-to-check-if-a-byte-array-is-a-valid-image & https://stackoverflow.com/questions/210650/validate-image-from-file-in-c-sharp – Sunil Nov 21 '17 at 01:51
  • This question is not a duplicate because its about a in memory bitmap construction. Its not about Bitmaps that get loaded from a file, and need validation testing. – Peter Jan 12 '18 at 12:57

1 Answers1

2

I think you can check the file header.

    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
}
James.YinG
  • 121
  • 2