新建文件dealImage.js
// dataBase64压缩
async function dealImage(base64, w, callback) {
return await new Promise((res, ret) => {
var newImage = new Image();
var file = "";
var quality = 0.6; //压缩系数0-1之间
newImage.src = base64;
newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要
var imgWidth, imgHeight;
// var ext = newImage.src.substring(newImage.src.indexOf(":")+1, newImage.src.indexOf(";base64")).toLowerCase();
// console.log('ext',ext,base64)
newImage.onload = function() {
imgWidth = this.width;
imgHeight = this.height;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w;
canvas.height = w * imgHeight / imgWidth;
} else {
canvas.height = w;
canvas.width = w * imgWidth / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
quality = 0.6;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
if (base64.length / 1024 < 50) {
res(base64)
return
} else {
while (base64.length / 1024 > 50) {
quality -= 0.002;
base64 = canvas.toDataURL("image/jpeg", quality);
}
//防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑
while (base64.length / 1024 < 48) {
quality += 0.001;
base64 = canvas.toDataURL("image/jpeg", quality);
}
}
file = base64;
console.log(file, '压缩后')
res(file)
}
})
}
export {
dealImage
}
引入(具体路径根据实际情况修改)
import {dealImage} from '../../../assets/js/littlebase64';
...
let item = await dealImage(dataItem, 500)
//其中dataItem参数是img src的值转换为base64字符,例如"data:image/png;base64,xxxxxxxx"
我的项目中是富文本编辑器添加了图片需要压缩,具体处理如下
async imgSizeChange(callback) {
//提交或者预览的时候才进行压缩图片,不在富文本change事件中进行压,缩,放置触发多变change事件
try{
let str = this._.cloneDeep(this.form.noticeContext);
var data = [];
str.replace(
/<img [^>]*src=['"]([^'"]+)[^>]*>/g,
function(match, capture) {
data.push(capture);
}
);
const arr = this._.cloneDeep(this.form.noticeContext).split('<img')
console.log('data---change-----', data, arr)
let imgArr = []
let indexArr = []
arr.map((item, index) => {
if(item.indexOf('src="') > -1){
imgArr.push(item)
//把下标记一下,放回来时需要
indexArr.push(index)
}
})
// console.log('imgArr111---', imgArr)
const res = await data.map(async (dataItem, index, array) => {
let item = await dealImage(dataItem, 500)
//把原来富文本中img的src值替换为压缩后的
imgArr[index] = imgArr[index].replace(/ [^>]*src=['"]([^'"]+)/ig, ` src="${item}`)
arr[indexArr[index]] = imgArr[index]
return item
});
const self= this
Promise.all(res).then(function(results) {
//这里的赋值在上边dealImage更改后改变也行,在这里也行,一下三行
// // results.map(async (item, index) => {
// // imgArr[index] = imgArr[index].replace(/ [^>]*src=['"]([^'"]+)/ig, ` src="${item}`)
// // arr[indexArr[index]] = imgArr[index]
// // })
const imgStr = arr.join('<img')
callback(imgStr)
})
}catch{
console.error('图片压缩错误')
//this.form.noticeContext 是富文本原来的内容
callback(this.form.noticeContext)
}
}
提交或者预览时进行压缩
this.imgSizeChange((res) => {
console.log('打印富文本中图片压缩之后的所有内容', res)
... //可以进行一下操作
})