2013-03-21 62 views
4

我想檢查從目錄中讀取的文件是否爲jpg,但我不想簡單地檢查擴展名。我正在考慮替代方案是閱讀標題。我做了一些研究,我想用檢查文件是否是有效的jpg

ImageIO.read 

我所看到的,我不知道在哪裏何去何從的例子

String directory="/directory";  

BufferedImage img = null; 
try { 
    img = ImageIO.read(new File(directory)); 
} catch (IOException e) { 
    //it is not a jpg file 
} 

,它需要在整個目錄...但我需要目錄中的每個jpg文件。有人能告訴我我的代碼出了什麼問題或需要添加什麼?

謝謝!

+0

去哪裏從那裏取決於你想要做:) – Thihara 2013-03-21 04:47:52

+0

你可能要有點更具體的什麼是錯的。代碼是不是編譯,不做任何事情?從代碼中可以看出,你只是將警告或註釋所在的地方放在了警告中,如果它不是jpeg,它會警告你,否則,如果它確實是jpeg,就不會使用catch塊。 – BrianHall 2013-03-21 04:48:37

+0

@Thihara更新。謝謝! – Teddy13 2013-03-21 04:48:58

回答

4

您可以讀取存儲在緩衝圖像中的第一個字節。這會給你確切的文件類型

Example for GIF it will be 
GIF87a or GIF89a 

For JPEG 
image files begin with FF D8 and end with FF D9 

http://en.wikipedia.org/wiki/Magic_number_(programming)

試試這個

Boolean status = isJPEG(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg")); 
System.out.println("Status: " + status); 


private static Boolean isJPEG(File filename) throws Exception { 
    DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename))); 
    try { 
     if (ins.readInt() == 0xffd8ffe0) { 
      return true; 
     } else { 
      return false; 

     } 
    } finally { 
     ins.close(); 
    } 
} 
+1

對於JPEG,文件以包含段偏移量的標題開頭。字符「JFIF」[實際上出現在APP0段的開頭](http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format#File_format_structure)。 – 2013-03-21 05:10:08

+0

我嘗試了一些JPEG文件,但在某些情況下,讀取的整數是0xffd8ffe1,所以我認爲最好只檢查2個字節,即0xFFD8 – singularity 2016-08-12 12:27:35

1

您將需要得到讀者用來讀取格式,並檢查是否有可用於給定的文件沒有讀者......

String fileName = "Your image file to be read"; 
ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName)); 
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg"); 
booleam canRead = false; 
while (readers.hasNext()) { 
    try {   
     ImageReader reader = readers.next(); 
     reader.setInput(iis); 
     reader.read(0); 
     canRead = true; 
     break; 
    } catch (IOException exp) { 
    }   
} 

現在基本上,如果沒有讀者可以讀取該文件,那麼它是不是一個Jpeg格式

買者

這是否有可用於指定的文件格式,讀者纔會工作。它可能仍然是一個Jpeg,但沒有閱讀器可用於給定的格式...