如何使用 FileReader 和 VueJs 获取图像高度和图像宽度?

How can i get image height and image width with FileReader and VueJs?

我有一个输入类型文件

<input type="file" class="userUploadButton" name="image" accept="image/*" on-change={this.setImage}/>

和 Vue - 方法 "setImage"

    setImage(e){
        const file = e.target.files[0];

        if (!file.type.includes('image/')) {

            Vue.swal({
                title: 'Error!',
                text: 'This is no image',
                type: 'error',
            });

            return;
        }

        if(typeof FileReader === 'function'){

            const reader = new FileReader();

            reader.onload = (event) => {
                this.imgSrc = event.target.result;
                this.$refs.cropper.replace(event.target.result);
            };

            reader.readAsDataURL(file);

        }else{

            Vue.swal({
                title: 'Error',
                text: 'Your browser does not support FileReader API',
                type: 'error',
            });

        }

    },

在用户上传图片的那一刻,我必须检查这张图片的宽度和高度并停止上传(或删除图片)

其实文件只是一个文件,您需要使用new Image()从文件源创建一个图像。

请检查示例 here and the same type of question to here

使用下面的源代码

   var width, height;

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

   img = new Image();

   img.onload = function() {
       // here you got the width and height
       width = this.width;
       height = this.height;
   };

   img.onerror = function() {
       alert( "not a valid file: " + file.type);
   };

   img.src = _URL.createObjectURL(file);

希望对您有所帮助!!