Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { public static String getImageType(File file) { if (file == null || !file.exists()) { return null; } InputStream in = null; try { in = new FileInputStream(file); return getImageType(in); } catch (IOException e) { return null; } finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static String getImageType(InputStream in) { if (in == null) { return null; } try { byte[] bytes = new byte[8]; in.read(bytes); return getImageType(bytes); } catch (IOException e) { return null; } } public static String getImageType(byte[] bytes) { if (isJPEG(bytes)) { return "image/jpeg"; } if (isGIF(bytes)) { return "image/gif"; } if (isPNG(bytes)) { return "image/png"; } if (isBMP(bytes)) { return "application/x-bmp"; } return null; } private static boolean isJPEG(byte[] b) { if (b.length < 2) { return false; } return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8); } private static boolean isGIF(byte[] b) { if (b.length < 6) { return false; } return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a'; } private static boolean isPNG(byte[] b) { if (b.length < 8) { return false; } return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78 && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10 && b[6] == (byte) 26 && b[7] == (byte) 10); } private static boolean isBMP(byte[] b) { if (b.length < 2) { return false; } return (b[0] == 0x42) && (b[1] == 0x4d); } }