系统中某些图片可能已经被修改了后缀名,所以不能只是对后缀名进行判断。下面的示例代码就是如何判断一个图片的具体类型的。
publicstaticvoidmain(String[]args){
Filef=newFile("c://test.jpg");
if(f.exists()){
System.out.println(getFormatInFile(f));
}
}
//Returnstheformatoftheimageinthefile'f'.
//Returnsnulliftheformatisnotknown.
publicstaticStringgetFormatInFile(Filef){
returngetFormatName(f);
}
//Returnstheformatnameoftheimageintheobject'o'.
//Returnsnulliftheformatisnotknown.
privatestaticStringgetFormatName(Objecto){
try{
//Createanimageinputstreamontheimage
ImageInputStreamiis=ImageIO.createImageInputStream(o);
//Findallimagereadersthatrecognizetheimageformat
Iterator<ImageReader>iter=ImageIO.getImageReaders(iis);
if(!iter.hasNext()){
//Noreadersfound
returnnull;
}
//Usethefirstreader
ImageReaderreader=iter.next();
//Closestream
iis.close();
//Returntheformatname
returnreader.getFormatName();
}catch(IOExceptione){
//
}
//Theimagecouldnotberead
returnnull;
}
Filef=newFile("c://test.jpg");
if(f.exists()){
System.out.println(getFormatInFile(f));
}
}
//Returnstheformatoftheimageinthefile'f'.
//Returnsnulliftheformatisnotknown.
publicstaticStringgetFormatInFile(Filef){
returngetFormatName(f);
}
//Returnstheformatnameoftheimageintheobject'o'.
//Returnsnulliftheformatisnotknown.
privatestaticStringgetFormatName(Objecto){
try{
//Createanimageinputstreamontheimage
ImageInputStreamiis=ImageIO.createImageInputStream(o);
//Findallimagereadersthatrecognizetheimageformat
Iterator<ImageReader>iter=ImageIO.getImageReaders(iis);
if(!iter.hasNext()){
//Noreadersfound
returnnull;
}
//Usethefirstreader
ImageReaderreader=iter.next();
//Closestream
iis.close();
//Returntheformatname
returnreader.getFormatName();
}catch(IOExceptione){
//
}
//Theimagecouldnotberead
returnnull;
}