码迷,mamicode.com
首页 > 其他好文 > 详细

vue 图片优化

时间:2020-04-17 14:07:52      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:yar   eject   图片   int   span   ons   load   image   import   

npm i image-conversion --save

# or 

yarn add image-conversion
import { compress, compressAccurately } from "image-conversion";
// 要用前先引用
 
handleBefore(file) {
      /** 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 */
      return new Promise((resolve, reject) => {
        const _URL = window.URL || window.webkitURL;
        const isLt2M = file.size / 1024 / 1024 > 2; // 判定图片大小是否小于4MB
        // 这里需要计算出图片的长宽
        const img = new Image();
        img.onload = function() {
          file.width = img.width; // 获取到width放在了file属性上
          file.height = img.height; // 获取到height放在了file属性上
          const imgwidth = img.width > 1280; // 图片宽度
          const imgheight = img.height > 1280; // 图片高度
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (imgwidth && isLt2M && imgheight) {
            compressAccurately(file, {
              size: 2048,
              width: 1280,
              height: 1280
            }).then(res => {
              resolve(res);
            });
          } else if (imgwidth && isLt2M) {
            compressAccurately(file, {
              size: 2048,
              width: 1280
            }).then(res => {
              resolve(res);
            });
          } else if (imgheight && isLt2M) {
            compressAccurately(file, {
              size: 2048,
              height: 1280
            }).then(res => {
              resolve(res);
            });
          } else if (imgheight && imgwidth) {
            compressAccurately(file, {
              width: 1280,
              height: 1280
            }).then(res => {
              resolve(res);
            });
          } else if (isLt2M) {
            compressAccurately(file, {
              size: 2048
            }).then(res => {
              resolve(res);
            });
          } else if (imgwidth) {
            compressAccurately(file, {
              width: 1280
            }).then(res => {
              resolve(res);
            });
          } else if (imgheight) {
            compressAccurately(file, {
              height: 1280
            }).then(res => {
              resolve(res);
            });
          } else resolve(file);
        }; // 需要把图片赋值
        img.src = _URL.createObjectURL(file);
      });
    },

vue 图片优化

标签:yar   eject   图片   int   span   ons   load   image   import   

原文地址:https://www.cnblogs.com/tongshuangxiong/p/12719463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!