首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Javascript上传前检查图像的宽度和高度

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

Stack Overflow用户
提问于 2012-01-18 08:57:59
回答 10查看 265K关注 0票数 165

我有一个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

有什么建议吗?

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-01-18 09:22:55

文件只是一个文件,您需要创建一个镜像,如下所示:

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/

我想你应该知道这只在几个浏览器中被支持。主要是火狐和chrome,现在也可能是opera了。

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

有关更多信息,请参阅here

票数 250
EN

Stack Overflow用户

发布于 2017-12-13 14:04:35

在我看来,你必须要的完美答案是

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;
  };
};
票数 57
EN

Stack Overflow用户

发布于 2012-01-18 09:04:23

我同意。一旦它被上传到用户的浏览器可以访问的地方,那么就很容易获得大小。由于您需要等待图像加载,因此您需要挂接imgonload事件。

更新示例:

// async/promise function for retrieving image dimensions for a URL
function imageSize(url) {
    const img = document.createElement("img");

    const promise = new Promise((resolve, reject) => {
      img.onload = () => {
        // Natural size is the actual image size regardless of rendering.
        // The 'normal' `width`/`height` are for the **rendered** size.
        const width  = img.naturalWidth;
        const height = img.naturalHeight; 

        // Resolve promise with the width and height
        resolve({width, height});
      };

      // Reject promise on error
      img.onerror = reject;
    });

    // Setting the source makes it start downloading and eventually call `onload`
    img.src = url;

    return promise;
}

// How to use in an async function
(async() => {
  const imageUrl = 'http://your.website.com/userUploadedImage.jpg';
  const imageDimensions = await imageSize(imageUrl);

  console.info(imageDimensions); // {width: 1337, height: 42}
})();

较老的示例:

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";
票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8903854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档