`
izuoyan
  • 浏览: 8958077 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

阅读更多
系统中某些图片可能已经被修改了后缀名,所以不能只是对后缀名进行判断。下面的示例代码就是如何判断一个图片的具体类型的。
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;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics