<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="canvas"> </canvas>
<!-- <img src="" alt=""> -->
<input type="file" />
</body>
</html>
<script>
let input = document.querySelector("input");
let canvas = document.querySelector("#canvas");
input.addEventListener("change", function (e) {
let file = input.files[0];
// console.log(file, "input.files[0]");
let reader = new FileReader();
reader.onload = function (e) {
let img = document.createElement("img");
img.src = e.target.result;
// console.log(e.target.result, "e.target.result");
/*获取base64后 下载到本地 开始*/
downLoadimg(e);
/*获取base64后 下载到本地 结束*/
img.onload = function () {
let base64 = compressImg(img);
let img222 = document.createElement("img");
img222.src = base64;
document.body.appendChild(img222);
};
};
reader.readAsDataURL(file);
});
function downLoadimg(e) {
let base64 = e.target.result;
let parts = base64.split(";base64,");
let contentType = parts[0].split(":")[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
let blob = new Blob([uInt8Array], { type: contentType });
let url = URL.createObjectURL(blob);
let downlod = document.createElement("a");
downlod.href = url;
downlod.download = "test.jpg";
downlod.click();
}
function compressImg(img) {
/*利用canvas对本地上传图片进行压缩*/
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
//铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
//压缩
let base64 = canvas.toDataURL("image/jpeg", 0.3);
//对比压缩前后的大小 压缩率
console.log("压缩前:" + img.src.length);
console.log("压缩后:" + base64.length);
console.log(
"压缩率:" + ~~((1 - base64.length / img.src.length) * 100) + "%"
);
//把压缩后的base64赋值给img的src
// img.src = base64;
return base64;
}
</script>
canvas 将本地上传图片压缩 和 拿到base64 转二进制 下载到本地
于 2023-10-31 18:50:45 首次发布