Check image width and height before upload with Javascript

前端 未结 8 845
情歌与酒
情歌与酒 2020-11-22 14:53

I have a JPS with a form in which a user can put an image:

Photo (max 240x240 and 100 kb):
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 15:35

    The file is just a file, you need to create an image like so:

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

    Demo: http://jsfiddle.net/4N6D9/1/

    I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.

    P.S. The URL.createObjectURL() method has been removed from the MediaStream interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL() to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.

    For more information, please refer here.

提交回复
热议问题