JAva判定画像フォーマット
1454 ワード
public static String getImageType() throws IOException {
FileInputStream fis = new FileInputStream("PATH");
int leng = fis.available();
BufferedInputStream buff = new BufferedInputStream(fis);
byte[] mapObj = new byte[leng];
buff.read(mapObj, 0, leng);
String type = "";
ByteArrayInputStream bais = null;
MemoryCacheImageInputStream mcis = null;
try {
bais = new ByteArrayInputStream(mapObj);
mcis = new MemoryCacheImageInputStream(bais);
Iterator itr = ImageIO.getImageReaders(mcis);
while (itr.hasNext()) {
ImageReader reader = (ImageReader) itr.next();
if (reader instanceof GIFImageReader) {
type = "gif";
} else if (reader instanceof JPEGImageReader) {
type = "jpeg";
} else if (reader instanceof PNGImageReader) {
type = "png";
} else if (reader instanceof BMPImageReader) {
type = "bmp";
}
}
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException ioe) {
}
}
if (mcis != null) {
try {
mcis.close();
} catch (IOException ioe) {
}
}
}
return type;
}