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