ITeye博客

Java中对图片文件的类型的获取

mmdev · 2007-11-28 10:22 · Markdown

系统中某些图片可能已经被修改了后缀名,所以不能只是对后缀名进行判断。下面的示例代码就是如何判断一个图片的具体类型的。

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;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。