Skip to content
the poor coder

javascript check if is image

Poor Man
Published
Reading time
1 min read
On this page

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.

JavaScript

      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.

JavaScript

      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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC