Easily find image type in JavaScript

There are two easy ways to determine an image’s type using JavaScript: using an html Input tag with a type file, and using the DataView API. I’ve put together a github repository that contains all the code shown below. The sample app detects PNG, GIF, JPEG and BMP: https://github.com/andygup/DetectImageType.js

Here’s how to do it with an Input tag:

    <input type="file" id="fileInput" name="file"/>
    <script>
    var fileInput = document.getElementById("fileInput");
    fileInput.addEventListener("change",function(event){
        document.getElementById("name").innerHTML = "NAME: " + event.target.files[0].name;
        document.getElementById("type").innerHTML = "TYPE: " + event.target.files[0].type;
        document.getElementById("size").innerHTML = "SIZE: " + event.target.files[0].size;
    });
    </script>

And, here’s how to do it with the DataView API. The concept is to retrieve the image via an HTTP request with the response type set to “arraybuffer.” And then extract the hexadecimal signature or magic number of the image type. I’ve taken the liberty of only reading the first 2 bytes to get the magic numbers in my example. If you need more precision here’s a great site to use for more information on image signatures: https://www.filesignatures.net/index.php?page=search

  function getImageType(arrayBuffer){
        var type = "";
        var dv = new DataView(arrayBuffer,0,5);
        var nume1 = dv.getUint8(0,true);
        var nume2 = dv.getUint8(1,true);
        var hex = nume1.toString(16) + nume2.toString(16) ;

        switch(hex){
            case "8950":
                type = "image/png";
                break;
            case "4749":
                type = "image/gif";
                break;
            case "424d":
                type = "image/bmp";
                break;
            case "ffd8":
                type = "image/jpeg";
                break;
            default:
                type = null;
                break;
        }
        return type;
    }

The DataView API has really good browser support. The only issues you’ll have, not surprisingly, are with IE 8 and 9. For more info on support of the DataView API go here: https://caniuse.com/#search=dataview