【问题标题】:Image.width gives 0Image.width 给出 0
【发布时间】:2020-05-16 21:35:28
【问题描述】:

我正在使用一个函数来验证上传图像的大小。效果很好,现在我还想检查图像是否比某些像素(如 1280 像素)宽。但是 var 宽度仍然为零。我已经尝试过使用outerwith、innerwidth和file.files[0].width;

function ValidateSize(file) {
    var FileSize = file.files[0].size / 1024 / 1024; // in MB
    var NewFilze = FileSize.toFixed(2);

    var height = file.height;
    var width = file.width;

    if (FileSize > 13) {
        alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
    }else if(width < 1280){
        alert("The width of your image  (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
    }else{

    }
}

提前致谢

【问题讨论】:

  • 此时文件对象是什么样子的。它有 .width 和 .height 吗?
  • 对于尺寸,您从file.files[0] 获取数据,但对于高度和宽度,您只需检查file filefile.files 应该是什么 - 有什么区别?
  • 因为它可以检测文件大小,我假设它可以检测到 with 和 height。
  • 也许也许不是。文件对象可能只是一个文件。您可能需要考虑先将文件转换为图像。
  • 看看使用 FileReader 然后转换成 Image。这个问题非常彻底地涵盖了它:stackoverflow.com/questions/7460272/…

标签: javascript


【解决方案1】:

由于无法自行测试,我建议尝试以下方法:

function ValidateSize(file) {
  var FileSize = file.files[0].size / 1024 / 1024; // in MB
  var NewFilze = FileSize.toFixed(2);
  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 (FileSize > 13) {
       alert("The file size of your picture (" + NewFilze + " MB) exceeds the maximum allowed filesize (12,5 MB). Still problems with resizing your pictures? Use for example www.imageresize.org.");
    }else if(width < 1280){
       alert("The width of your image  (" + width + " pixels) is lower than the required minimum width (1280 pixels)");
    }else{

    }
} 

我应该注意到这是未经测试的,并且取决于您在某些浏览器(理想情况下是 chrome 或 FF)上运行的 js。如果是服务器端,我认为 visibleman 是最好的答案。

祝你好运,黑客愉快!!

归功于SO post where I got the image code

【讨论】:

  • 这个是对的,不知道为什么我只是假设它是服务器端的。
  • 该功能看起来应该是服务器端的,但我更多的是前端人员,所以我想为什么不尝试前端解决方案。
【解决方案2】:

您需要将文件转换成图片:

这是一个如何将文件转换为 img 以获得宽度和高度的示例:

function getSize(file) {
    const img = new Image();
    var file = file.files[0];
    var reader = new FileReader();
    reader.addEventListener("load", function() {
        img.src = reader.result;
    }, false);
    const promise = new Promise((resolve, reject) => {
        img.onload = () => {
            console.log(img.naturalWidth, img.naturalHeight);
            resolve([img.naturalWidth, img.naturalHeight]);
        };
    });
    if (file) {
        reader.readAsDataURL(file);
    }
    return promise.then(res => [img.naturalWidth, img.naturalHeight]);
}

您可以进行一些更改以使其适用于您的情况。祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2020-10-28
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 2022-07-26
    相关资源
    最近更新 更多