LoginSignup
11
14

More than 5 years have passed since last update.

画像のファイルタイプをバイナリヘッダで判定する

Last updated at Posted at 2013-11-26
import static org.apache.commons.codec.binary.Hex.encodeHexString;
import static org.apache.commons.io.FileUtils.openInputStream;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.apache.commons.io.IOUtils.toByteArray;

public static String getFileHeader(File f) {
    if (f.length() == 0) {
        return null;
    } else {
        byte[] b = new byte[8];
        InputStream in = null;
        try {
            in = openInputStream(f);
            b = toByteArray(in, 8);
        } catch (IOException e) {
            return "";
        } finally {
            closeQuietly(in);
        }
        return encodeHexString(b);
    }
}

public static boolean isImage(File image) {
    if (image == null) {
        return false;
    }
    String fileHeader = getFileHeader(image);
    if (fileHeader == null || fileHeader.isEmpty()) {
        return false;
    }
    fileHeader = fileHeader.toUpperCase();
    if (fileHeader.equals("89504E470D0A1A0A")) { // PNG
        return true;
    } else if (fileHeader.matches("^FFD8.*")) { // JPG
        return true;
    } else if (fileHeader.matches("^474946383961.*") || fileHeader.matches("^474946383761.*")) { // GIF
        return true;
    } else if (fileHeader.matches("^424D.*")) { // BMP
        return true;
    }
    return false;
}
11
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14