2017-11-21 3 views
1

Ich versuche, dieses ZielWie „ist gültig Image File“ zu überprüfen, in C#

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

Aber wenn test.jpg ist Schaden dann wird C# zeigen zu erreichen nicht try-catch mit Fehler, also meine Frage: Gibt es in C# eine Funktion wie IsValidImage()?

THX!

+0

Hoffnung könnte dies helfen https://stackoverflow.com/a/210667/3583859 –

+0

Duplizieren von 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

+0

Diese Frage ist kein Duplikat, da es sich um eine im Speicher befindliche Bitmap-Konstruktion handelt . Es geht nicht um Bitmaps, die aus einer Datei geladen werden und Validierungstests benötigen. – user3800527

Antwort

1

Ich denke, dass Sie den Dateikopf überprüfen können.

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 
} 
+0

thx viel, aber _imageTag ist nicht definiert, warum ist das? – David4866

+0

es ist ein Mapping, int zum Bildtyp, wie: –

+0

es ist ein Dictionary , int zum Bildtyp, wie: _imageType [(int) ImageType.JPG] = ImageType.JPG –

Verwandte Themen