Java中對圖片檔案的型別的獲取
阿新 • • 發佈:2019-02-12
publicstaticvoid main(String[] args) {
File f =new File("c://test.jpg");
if (f.exists()) {
System.out.println(getFormatInFile(f));
}
}
// Returns the format of the image in the file 'f'.
// Returns null if the format is not known.publicstatic String getFormatInFile(File f) {
return getFormatName(f);
}
// Returns the format name of the image in the object 'o'.
// Returns null if the format is not known.privatestatic String getFormatName(Object o) {
try {
// Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(o);
// Find all image readers that recognize the image format Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
// No readers foundreturnnull;
}
// Use the first reader ImageReader reader = iter.next();
// Close stream iis.close();
// Return the format namereturn reader.getFormatName();
} catch (IOException e) {
//
}
// The image could not be readreturnnull;
}
File f =new File("c://test.jpg");
if (f.exists()) {
System.out.println(getFormatInFile(f));
}
}
// Returns the format of the image in the file 'f'.
// Returns null if the format is not known.publicstatic String getFormatInFile(File f) {
}
// Returns the format name of the image in the object 'o'.
// Returns null if the format is not known.privatestatic String getFormatName(Object o) {
try {
// Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(o);
if (!iter.hasNext()) {
// No readers foundreturnnull;
}
// Use the first reader ImageReader reader = iter.next();
// Return the format namereturn reader.getFormatName();
} catch (IOException e) {
//
}
// The image could not be readreturnnull;
}