系统中某些图片可能已经被修改了后缀名,所以不能只是对后缀名进行判断。下面的示例代码就是如何判断一个图片的具体类型的。
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;
}
本文提供了一段Java代码示例,用于检测文件系统中图片的真实格式,而不仅仅是依赖于文件的后缀名。通过使用Java的ImageIO类,可以读取图片文件并确定其实际的格式。
1780

被折叠的 条评论
为什么被折叠?



