Java で、画像バイナリデータ byte[] の状態のデータから image/jpeg などのタイプを調べます。
画像 File であれば、java.nio.file.Files の probeContentType(Path) を使えば良いのですが、
バイナリデータの状態から検査したい場合が稀にあるでしょう。
データの先頭8バイトをチェックすれば済みます。
ついでに画像の width と height も取得します。
import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; public static Map<String, String> getImageInfo(byte[] b) throws IOException{ Map<String, String> r = new HashMap<>(); try(ByteArrayInputStream bin = new ByteArrayInputStream(b)){ BufferedImage bimg = ImageIO.read(bin); r.put("width", Integer.toString(bimg.getWidth())); r.put("height", Integer.toString(bimg.getHeight())); } StringBuilder sb = new StringBuilder(); for(int i=0;i < 8;i++){ sb.append(String.format("%02x", b[i])); if (sb.toString().equals("ffd8")){ r.put("type", "image/jpeg"); break; } if (sb.toString().equals("424d")){ r.put("type", "image/bmp"); break; } if (sb.toString().equals("47494638")){ r.put("type", "image/gif"); break; } if (sb.toString().equals("49492a00")){ r.put("type", "image/tiff"); break; } if (sb.toString().equals("89504e470d0a1a0a")){ r.put("type", "image/png"); } } return r; }
File を指定しても同じメソッドをcall するようにラップしておくと良いでしょう。
public static Map<String, String> getImageInfo(File file) throws IOException{ try(InputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream()){ in.transferTo(out); out.flush(); return getImageInfo(out.toByteArray()); } }