javascript check if is image

JavaScript Check if Image

If you want to check if a file is an image using JavaScript, you can use the file's extension or MIME type.

Method 1: Checking File Extension

The simplest way to check if a file is an image is by looking at its file extension. Most image types have specific file extensions such as .jpg, .png, .gif, .bmp etc.


      function isImage(filename) {
        var ext = filename.split('.').pop();
        if (ext === 'jpg' || ext === 'png' || ext === 'gif' || ext === 'bmp') {
          return true;
        }
        return false;
      }
    

This function takes in a filename and splits it by the '.' character to get the file extension. It then checks if the extension matches any of the common image types and returns true if it does, and false if it doesn't.

Method 2: Checking MIME Type

Another way to check if a file is an image is by looking at its MIME type. MIME types describe the type of data contained in a file and can be accessed using the FileReader API.


      function isImage(file) {
        return /^image\//.test(file.type);
      }
    

This function takes in a file object and uses a regular expression to test if the file's MIME type starts with 'image/'. This will match any image type such as image/jpeg, image/png etc.

Conclusion

Both of these methods can be used to check if a file is an image using JavaScript. The first method is simpler but may not be as reliable as some file extensions may not match their actual type. The second method is more reliable but requires access to the FileReader API.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe