使用Javascript上传之前检查图像的宽度和高度


122

我有一个JPS,其中用户可以在其中放置图像:

<div class="photo">
    <div>Photo (max 240x240 and 100 kb):</div>
    <input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>

我写了这个js:

function checkPhoto(target) {
    if(target.files[0].type.indexOf("image") == -1) {
        document.getElementById("photoLabel").innerHTML = "File not supported";
        return false;
    }
    if(target.files[0].size > 102400) {
        document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
        return false;
    }
    document.getElementById("photoLabel").innerHTML = "";
    return true;
}

可以很好地检查文件类型和大小。现在,我想检查图像的宽度和高度,但是我不能这样做。
我已经尝试过,target.files[0].width但是我得到了undefined。用其他方式我得到0
有什么建议?

Answers:


221

该文件只是一个文件,您需要像这样创建一个图像:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        var objectUrl = _URL.createObjectURL(file);
        img.onload = function () {
            alert(this.width + " " + this.height);
            _URL.revokeObjectURL(objectUrl);
        };
        img.src = objectUrl;
    }
});

演示:http : //jsfiddle.net/4N6D9/1/

我认为您意识到只有少数浏览器才支持。到现在为止,大多数都是Firefox和Chrome,也可以成为歌剧。

PS URL.createObjectURL()方法已从MediaStream接口中删除。此方法已在2013年弃用,并通过将流分配给HTMLMediaElement.srcObject来取代。删除了旧方法,因为它不太安全,需要调用URL.revokeOjbectURL()才能结束流。其他用户代理已弃用(Firefox)或已删除(Safari)此功能。

有关更多信息,请参阅此处


1
除非您拥有Safari 6.0,否则它将无法在Safari中正常使用。到目前为止,6.0是唯一支持文件API的版本。而且我认为苹果不会为Windows发布6.0。5.1.7已经Safari浏览器的最新VERSON从SOOOO很久以前
SEHO李

它可以在IE10中使用,但似乎不能在IE9及以下版本中使用。那是因为IE9及以下版本不支持File API(caniuse.com/#search=file%20api
Michael Yagudaev 2013年

28

我认为您必须要求的完美答案是

var reader = new FileReader();

//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {

//Initiate the JavaScript Image object.
var image = new Image();

//Set the Base64 string return from FileReader as source.
image.src = e.target.result;

//Validate the File Height and Width.
image.onload = function () {
  var height = this.height;
  var width = this.width;
  if (height > 100 || width > 100) {
    alert("Height and Width must not exceed 100px.");
    return false;
  }
  alert("Uploaded image has valid Height and Width.");
  return true;
};

18

我同意。将其上传到用户浏览器可以访问的位置后,就很容易获得大小。当您需要等待图片加载时,您需要加入的onload事件img

var width, height;

var img = document.createElement("img");
img.onload = function() {
    // `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
    // The natural size is the actual image size regardless of rendering.
    // The 'normal' width/height are for the **rendered** size.

    width  = img.naturalWidth  || img.width;
    height = img.naturalHeight || img.height; 

    // Do something with the width and height
}

// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";

7

这是检查尺寸的最简单方法

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

检查特定尺寸。以100 x 100为例

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.`);
   }                
}

2

函数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;
        }
    }

1
请尝试格式化完整的代码,并提供一些有关您在代码中所做的工作的描述。
Zeeshan Adil

2

将该函数附加到输入类型文件的onchange方法/ onchange =“ validateimg(this)” /

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        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;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            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;
        }
    }

0

    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;
        }
    }


-1
function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

欢迎使用Stack Overflow!请不要只回答源代码。尝试提供有关您的解决方案如何工作的很好的描述。请参阅:我如何写一个好的答案?。谢谢
sɐunıɔןɐqɐp
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.