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

Sim*_*mon 97 javascript file-upload image image-size

我有一个JPS,其中包含一个用户可以放置图像的表单:

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

我写过这个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;
}
Run Code Online (Sandbox Code Playgroud)

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

Esa*_*ija 192

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

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

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

我认为这只是在少数浏览器中支持的.主要是firefox和chrome,现在也可以是歌剧.

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

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


pse*_*ant 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";
Run Code Online (Sandbox Code Playgroud)


小智 18

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

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

检查具体尺寸。以 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.`);
   }                
}
Run Code Online (Sandbox Code Playgroud)

  • 请记住调用 URL.revokeObjectURL() 以避免内存泄漏。https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL (3认同)

ash*_*das 13

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

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;
};
Run Code Online (Sandbox Code Playgroud)

  • 我用 13 MB 的图像文件尝试了该代码。浏览器最多需要 2 秒的时间来处理并返回宽度/高度。然而,最重要的答案是在几毫秒内获得图像尺寸。 (3认同)
  • @Avatar,您应该说明谁发布了最热门的答案,因为最热门的答案会随着时间的推移而变化。 (2认同)

E G*_*E G 13

我认为如果你想使用它的其他功能,这可能是最简单的上传功能。

async function getImageDimensions(file) {
    let img = new Image();
    img.src = URL.createObjectURL(file);
    await img.decode();
    let width = img.width;
    let height = img.height;
    return {
        width,
        height,
    }
  }
Run Code Online (Sandbox Code Playgroud)

使用类似

 const {width, height } = await getImageDimensions(file)
Run Code Online (Sandbox Code Playgroud)

假设您正在存储一张在肯尼亚拍摄的老虎图像。所以你可以像上传到云存储然后存储照片信息一样使用它。

const addImage = async (file, title, location) => {
   const { width, height } = await getImageDimensions(file)
   
   const url = await uploadToCloudStorage(file) // returns storage url

   await addToDatabase(url, width, height, title, location)
}
Run Code Online (Sandbox Code Playgroud)


小智 6

将函数附加到输入类型文件的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;
        }
    }
Run Code Online (Sandbox Code Playgroud)


Jos*_*Fdo 5

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)