Check image width and height before upload with Javascript

前端 未结 8 754
情歌与酒
情歌与酒 2020-11-22 14:53

I have a JPS with a form in which a user can put an image:

Photo (max 240x240 and 100 kb):
相关标签:
8条回答
  • 2020-11-22 15:52

    This is the easiest way to check the size

    let img = new Image()
    img.src = window.URL.createObjectURL(event.target.files[0])
    img.onload = () => {
       alert(img.width + " " + img.height);
    }
    

    Check for specific size. Using 100 x 100 as example

    let img = new Image()
    img.src = window.URL.createObjectURL(event.target.files[0])
    img.onload = () => {
       if(img.width === 100 && img.height === 100){
            alert(`Nice, image is the right size. It can be uploaded`)
            // upload logic here
            } else {
            alert(`Sorry, this image doesn't look like the size we wanted. It's 
       ${img.width} x ${img.height} but we require 100 x 100 size image.`);
       }                
    }
    
    0 讨论(0)
  • 2020-11-22 15:57

        const ValidateImg = (file) =>{
            let img = new Image()
            img.src = window.URL.createObjectURL(file)
            img.onload = () => {
                if(img.width === 100 && img.height ===100){
                    alert("Correct size");
                    return true;
                }
                alert("Incorrect size");
                return true;
            }
        }

    0 讨论(0)
提交回复
热议问题