思路: 先通过input 标签上传图片,用FileReader对象来加载文件,new一个image对象,用来获取原来的宽和高,图片大小超过限定的访问后进行压缩。再将image对象以想要的高宽画到canvas上,最后用canvas.toDataURL()方法获取压缩后的图片base64。
重点:canvas
核心代码
// 压缩图片并返回base64
function getBase64(fileDocument) {
// 新增遮罩
var loadIndex = layer.load(1, {
shade: [0.6, '#fff'], //0.6透明度的白色背景
offset: ['40%'],
time: 10 * 1000,
});
var file = fileDocument.files[0];
var fileName = fileDocument.value;
// 配置参数
var sizeList = [1,0.8,0.7];
var typeList = [".jpg",".png",".jpeg"];
var afterType = "image/jpeg";
return new Promise((resolve, reject) => {
try {
//静默处理
if (fileName == null) {
fileName = "";
layer.close(loadIndex);
resolve("error");
}
var seat = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
var typeCheck = false;
typeList.forEach(e => {
if (e == seat) {
typeCheck = true;
}
});
if (!typeCheck) {
layer.close(loadIndex);
layer.msg("只能上传图片文件!");
fileName = "";
resolve("error");
}
var size;
var fileSize = Math.round(file.size / (1024 * 1024));
if (fileSize < 2) {
size = sizeList[0];
} else if (fileSize >= 2 && fileSize < 5) {
size = sizeList[1];
} else if (fileSize >= 5 && fileSize < 10) {
size = sizeList[2];
} else {
layer.msg("图片大小超过10M!上传失败!");
// 清空所选择文件路径
fileName = "";
resolve("error");
}
var img = new Image();
var reader = new FileReader();
reader.onload = function (e) {
// 文件加载成功后去转成Img对象,为了拿到图片的原始宽高
img.src = e.target.result;
img.onload = function () {
// 创建画布canvas
let canvas = document.createElement('canvas');
let content = canvas.getContext('2d');
// 设置画布的宽高
canvas.width = img.width * size; // 需要压缩到的图片宽度
canvas.height = img.height * size;
// 将图片画在画布上
content.drawImage(img, 0, 0, canvas.width, canvas.height);
// console.log(canvas.toDataURL('image/jpeg', 0.92));
layer.close(loadIndex);
resolve(canvas.toDataURL(afterType, 0.92));
}
};
reader.readAsDataURL(file);
//转 失败
reader.onerror = function (error) {
layer.close(loadIndex);
reject(error);
};
} catch (e) {
// ignore
}
});
};
全部代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.4.0/layer.js"></script>
<title>Document</title>
</head>
<body>
<input id="uploadBack" type="file" />
<button id="upLoad">提交</button>
<div id="images">
</div>
<script>
$(function () {
// 压缩图片并返回base64
function getBase64(fileDocument) {
// 新增遮罩
var loadIndex = layer.load(1, {
shade: [0.6, '#fff'], //0.6透明度的白色背景
offset: ['40%'],
time: 10 * 1000,
});
var file = fileDocument.files[0];
var fileName = fileDocument.value;
// 配置参数
var sizeList = [1,0.8,0.7];
var typeList = [".jpg",".png",".jpeg"];
var afterType = "image/jpeg";
return new Promise((resolve, reject) => {
try {
//静默处理
if (fileName == null) {
fileName = "";
layer.close(loadIndex);
resolve("error");
}
var seat = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
var typeCheck = false;
typeList.forEach(e => {
if (e == seat) {
typeCheck = true;
}
});
if (!typeCheck) {
layer.close(loadIndex);
layer.msg("只能上传图片文件!");
fileName = "";
resolve("error");
}
var size;
var fileSize = Math.round(file.size / (1024 * 1024));
if (fileSize < 2) {
size = sizeList[0];
} else if (fileSize >= 2 && fileSize < 5) {
size = sizeList[1];
} else if (fileSize >= 5 && fileSize < 10) {
size = sizeList[2];
} else {
layer.msg("图片大小超过10M!上传失败!");
// 清空所选择文件路径
fileName = "";
resolve("error");
}
var img = new Image();
var reader = new FileReader();
reader.onload = function (e) {
// 文件加载成功后去转成Img对象,为了拿到图片的原始宽高
img.src = e.target.result;
img.onload = function () {
// 创建画布canvas
let canvas = document.createElement('canvas');
let content = canvas.getContext('2d');
// 设置画布的宽高
canvas.width = img.width * size; // 需要压缩到的图片宽度
canvas.height = img.height * size;
// 将图片画在画布上
content.drawImage(img, 0, 0, canvas.width, canvas.height);
// console.log(canvas.toDataURL('image/jpeg', 0.92));
layer.close(loadIndex);
resolve(canvas.toDataURL(afterType, 0.92));
}
};
reader.readAsDataURL(file);
//转 失败
reader.onerror = function (error) {
layer.close(loadIndex);
reject(error);
};
} catch (e) {
// ignore
}
});
};
$("#upLoad").off('click').on('click', function () {
getBase64($("#uploadBack")[0]).then(function(data){
console.log(data);
$("#images").html(`<img src="${data}" width="500px" srcset="">`)
})
})
})
</script>
</body>
</html>
评论区