Java

Get Image File Type from magic numbers

Magic numbers are the first bits of a file which uniquely identify the type of the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class FileIdentifier {
    private final int BMP = 0x424d;
    private final int GIF = 0x47494638;
    private final int JPEG = 0xffd8ffe0;
    private final int PNG = 0x89504e47;
 
    /**
     * get image file type based on file first bytes - magic number
     * @param filename
     * @return format name
     */
    public String getImageFileType(String filename) {
        try {
            try (DataInputStream input = new DataInputStream(
                         new BufferedInputStream(
                         new FileInputStream(filename)))) {
                for (int i = 0; i < 1; i++){
                    switch(input.readInt()){
                        case BMP:
                            return "bitmap";
                        case GIF:
                            return "gif";
                        case JPEG:
                            return "jpeg";
                        case PNG:
                            return "png";
                        default:
                            return "Unknown format";
                    }
                }
                return "Unknown format";
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
            return "Unknown format";
        }
    }
}