<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<input id="input" type="file" value=""></input>
<script>
document.querySelector("#input").onchange = function() {
const file = this.files[0]
compressImage(file, file => {
let alink = document.createElement('a')
alink.href = URL.createObjectURL(file)
alink.download = file.name
alink.click()
})
}
compressImage = (file, success) => {
const name = file.name.split('.')[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
const src = e.target.result;
const img = new Image();
img.src = src;
img.onload = e => {
const w = img.width;
const h = img.height;
const quality = 1;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const anw = document.createAttribute("width");
anw.nodeValue = w;
const anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
const base64 = canvas.toDataURL('image/jpeg', quality);
console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`);
const bytes = window.atob(base64.split(',')[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
file = new Blob([ab], {type : 'image/jpeg'});
file.name = name;
success(file);
}
img.onerror = e => {
console.log(e);
}
}
reader.onerror = e => {
console.log(e);
}
}
</script>
</body>
</html>