Check image width and height before upload with Javascript

前端 未结 8 732
情歌与酒
情歌与酒 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:47

    function validateimg(ctrl) {

            var fileUpload = $("#txtPostImg")[0];
    
    
            var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
            if (regex.test(fileUpload.value.toLowerCase())) {
    
                if (typeof (fileUpload.files) != "undefined") {
    
                    var reader = new FileReader();
    
                    reader.readAsDataURL(fileUpload.files[0]);
                    reader.onload = function (e) {
    
                        var image = new Image();
    
                        image.src = e.target.result;
                        image.onload = function () {
    
                            var height = this.height;
                            var width = this.width;
                            console.log(this);
                            if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
                                alert("Height and Width must not exceed 1100*800.");
                                return false;
                            }
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        };
                    }
                } else {
                    alert("This browser does not support HTML5.");
                    return false;
                }
            } else {
                alert("Please select a valid Image file.");
                return false;
            }
        }
    

提交回复
热议问题