vue 图片优化

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);       });     },
上一篇:FFR总结


下一篇:1280 尼克任务