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!

3

1 Answer 1

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

thx a lot, but _imageTag is not define, why is that?
it's a mapping,int to image type,like:
it's a Dictionary<int, ImageType>,int to image type,like: _imageType[(int)ImageType.JPG] = ImageType.JPG

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.