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

旧时模样 提交于 2019-12-10 19:24:31

问题


I have an input type file

<input type="file" class="userUploadButton" name="image" accept="image/*" on-change={this.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)


回答1:


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.

Use the following source code

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

Hopes this will help you!!



来源:https://stackoverflow.com/questions/49004162/how-can-i-get-image-height-and-image-width-with-filereader-and-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!