📄 e698. determining the format of an image in a file.txt
字号:
The javax.imageio package can determine the type of image in a file or input stream.
try {
// Get image format in a file
File file = new File("image.gif");
String formatName = getFormatName(file);
// e.g. gif
// Get image format from an input stream
InputStream is = new FileInputStream(file);
formatName = getFormatName(is);
is.close();
} catch (IOException e) {
}
// Returns the format of the image in the file 'f'.
// Returns null if the format is not known.
public static String getFormatInFile(File f) {
return getFormatName(f);
}
// Returns the format of the image in the input stream 'is'.
// Returns null if the format is not known.
public static String getFormatFromStream(InputStream is) {
return getFormatName(is);
}
// Returns the format name of the image in the object 'o'.
// 'o' can be either a File or InputStream object.
// Returns null if the format is not known.
private static 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 iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
// No readers found
return null;
}
// Use the first reader
ImageReader reader = (ImageReader)iter.next();
// Close stream
iis.close();
// Return the format name
return reader.getFormatName();
} catch (IOException e) {
}
// The image could not be read
return null;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -