简体   繁体   中英

How to check image width and height before upload

for picture upload i wrote following html code :

<input type="file" id="upload" class="im" onchange="fileSelectHandlerProfile('defaultProfile','true')" style="cursor:pointer"/>

when we done with select image,

this code will be fired :

function fileSelectHandlerProfile(title, defalutProfile) {
    var oFile;
    oFile = $('#thumbUploadProfile')[0].files[0];
    var rFilter = /^(image\/jpeg|image\/png|image\/gif|image\/bmp|image\/jpg|image\/pjpeg)$/i;
    if (!rFilter.test(oFile.type)) {
        $('.errorProfile').html('Please select a valid image file (jpg and png are allowed)').show();
    }
}

i want to check the oFile width and height, how can it is possible like oFile.type?

A solutions is to load it clienside and check the height and width.

function fileSelectHandlerProfile(title, defalutProfile) {
var oFile;
oFile = $('#thumbUploadProfile')[0].files[0];
var rFilter = /^(image\/jpeg|image\/png|image\/gif|image\/bmp|image\/jpg|image\/pjpeg)$/i;
if (!rFilter.test(oFile.type)) {
    $('.errorProfile').html('Please select a valid image file (jpg and png are allowed)').show();
}

var picReader = new FileReader();

picReader.addEventListener("load", function (event) {

    var imageObj = new Image();
    imageObj.src = event.target.result;
    imageObj.onload = function () {
        //TEST IMAGE SIZE
        if (imageObj.height < 100 || imageObj.width < 100) {
            $('.errorProfile').html('Please select an image with correct dimensions').show();
        }
    };
});

//Read the image
picReader.readAsDataURL(oFile);

}

You can do it in 2 steps:

  1. Read the image file content as data url using html5 file api:
var reader  = new FileReader();
reader.onloadend = function () {
    //var dataUrl = reader.result;
    //code as per step 2 here...
}
reader.readAsDataURL(oFile);

//ref: https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL
  1. Now read the image size by creating Image object with the dataUrl as src.

    Details: JS - get image width and height from the base64 code

The FileReader API allows you to use FileReader.readAsDataURL to read the file as a data: url. Use that url as the src attribute of a <img /> tag and read the width and height attribute of that image.

    var width;
    var height;
    var oFile;
    oFile = $('#thumbUploadProfile')[0].files[0];

    var reader = new FileReader();
    reader.onload = function(e){
        var image = new Image();
        image.onload  = function(){            
            width = img.width;
            height = img.height;
        }
        image.src   = e.target.result;
    };
    reader.readAsDataURL(oFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM