如何使用FileReader和VueJs获得图像高度和图像宽度? [英] How can i get image height and image width with FileReader and VueJs?

查看:477
本文介绍了如何使用FileReader和VueJs获得图像高度和图像宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入类型文件

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

和Vue-方法"setImage"

and Vue - method "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',
            });

        }

    },

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

In the moment when user upload an image, I have to check width and height of this image and stop uploading (or delete the image)

推荐答案

实际上,该文件只是一个文件,您需要使用new Image()从文件源创建图像.

Actually, the file is just a file, you need to create an image using new Image() from the file source.

请在此处中查看示例,并对

Please check example to 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);

希望这对您有帮助!

这篇关于如何使用FileReader和VueJs获得图像高度和图像宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆