Javascript 上传前是否可以检查图像的尺寸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13572129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:23:24  来源:igfitidea点击:

Is it possible to check dimensions of image before uploading?

javascriptjqueryfile-uploadclient-side

提问by Sabby62

I have an upload control for uploading the images to the server, but before uploading I just want to make sure if the images are of correct dimensions. Is there anything on client side that can be done with JavaScript?

我有一个用于将图像上传到服务器的上传控件,但在上传之前我只想确保图像的尺寸是否正确。客户端有什么可以用 JavaScript 完成的吗?

回答by Esailija

You could check them before submitting form:

您可以在提交表单之前检查它们:

window.URL = window.URL || window.webkitURL;

$("form").submit( function( e ) {
    var form = this;
    e.preventDefault(); //Stop the submit for now
                                //Replace with your selector to find the file input in your form
    var fileInput = $(this).find("input[type=file]")[0],
        file = fileInput.files && fileInput.files[0];

    if( file ) {
        var img = new Image();

        img.src = window.URL.createObjectURL( file );

        img.onload = function() {
            var width = img.naturalWidth,
                height = img.naturalHeight;

            window.URL.revokeObjectURL( img.src );

            if( width == 400 && height == 300 ) {
                form.submit();
            }
            else {
                //fail
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        form.submit();
    }

});

This only works on modern browsers so you still have to check the dimensions on server side. You also can't trust the client so that's another reason you must check them server side anyway.

这仅适用于现代浏览器,因此您仍然需要检查服务器端的尺寸。您也不能信任客户端,因此这是您无论如何必须检查它们的服务器端的另一个原因。

回答by Gurpreet Singh

Yes, HTML5 API supports this.

是的,HTML5 API 支持这一点。

http://www.w3.org/TR/FileAPI/

http://www.w3.org/TR/FileAPI/

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {

    var image, file;

    if ((file = this.files[0])) {

        image = new Image();

        image.onload = function() {

            alert("The image width is " +this.width + " and image height is " + this.height);
        };

        image.src = _URL.createObjectURL(file);


    }

});?

DEMO(tested on chrome)

演示(在 chrome 上测试)

回答by Gabriel Ambrósio Archanjo

To make things simple, use a javascript image processing framework like fabric.js, processing.jsand MarvinJ.

为简单起见,请使用 javascript 图像处理框架,如fabric.jsprocessing.jsMarvinJ

In the case of MarvinJ, simply loads the image in the client side and use the methods getWidth()and getHeight()to check the image's dimensions. Having the dimensions you can allow the file submission or notify the user about the incompatible dimension.

MarvinJ的情况下,只需在客户端加载图像并使用getWidth()getHeight()方法检查图像的尺寸。拥有维度,您可以允许文件提交或通知用户有关不兼容维度的信息。

Example:

例子:

var image = new MarvinImage();
image.load("https://i.imgur.com/oOZmCas.jpg", imageLoaded);

function imageLoaded(){
  document.getElementById("result").innerHTML += image.getWidth()+","+image.getHeight();
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<div id="result"></div>

回答by Klemen Tu?ar

Might be a bit late but here's a modern ES6 version of the accepted answer using promises

可能有点晚了,但这是使用承诺的已接受答案的现代 ES6 版本

const getUploadedFileDimensions: file => new Promise((resolve, reject) => {
    try {
        let img = new Image()

        img.onload = () => {
            const width  = img.naturalWidth,
                  height = img.naturalHeight

            window.URL.revokeObjectURL(img.src)

            return resolve({width, height})
        }

        img.src = window.URL.createObjectURL(file)
    } catch (exception) {
        return reject(exception)
    }
})

You'd call it like this

你会这样称呼它

getUploadedFileDimensions(file).then(({width, height}) => {
    console.log(width, height)
})

回答by Kaiido

If you don't need to handle svg files and can limit yourself to newest browsers, then you can use the createImageBitmapfunction to make a Promise based one liner:

如果您不需要处理 svg 文件并且可以限制自己使用最新的浏览器,那么您可以使用该createImageBitmap函数来制作一个基于 Promise 的单行:

if(typeof createImageBitmap !== "function") {
  console.error("Your browser doesn't support this method");
  // fallback to URL.createObjectURL + <img>
}

inp.oninput = e => {
  createImageBitmap(inp.files[0])
    .then((bmp) => console.log(bmp.width, bmp.height))
    .catch(console.error);
}
<input type="file" id="inp" accept="image/*">

回答by webNoob

Give this a shot. I've used this in the past. https://github.com/valums/file-uploader

试一试。我过去用过这个。 https://github.com/valuems/file-uploader