Search code examples
javascripthtmlweb

Limit image proportions with JavaScript


<input type="file" id="file" accept="image/gif, image/jpeg, image/png">

The HTML code is structured as follows. In this case, if an image with a ratio of 1:1 is not entered in the input, I want to move to another page through JavaScript.


Solution

  • You basically need to add a handler for the input, and check if the height/width === 1, you can use this function to validate it:

    const fileUpload = document.getElementById("file");
    
    function validateImage(target) {
      const reader = new FileReader();
      reader.readAsDataURL(fileUpload.files[0]);
      reader.onload = function (e) {
    
        const image = new Image();
        image.src = e.target.result;
    
        image.onload = function () {
          const height = this.height;
          const width = this.width;
          
          if (height / width !== 1) {
            console.log("ASPECT RATIO NOT 1:1");
            window.location.href = "#otherpage"; // redirect
            return false;
          }
          
          // do nothing
          return true;
        };
      };
    }
    <input type="file" id="file" accept="image/gif, image/jpeg, image/png"  onchange="validateImage(this)">

    Note that this is a very simple validation, normally you would want to add error handlers (e.g. invalid file, broken image, etc.).