工作中,经常需要压缩图片,比如ui给的图是1024 * 1024像素的,但是我们只是放到移动端里面使用,这么大的像素对我们来说毫无意义,顶多弄到300 * 300就ok了
像素减少带来的体积变化非常的明细 看下图就知道了
所以没事干写了个html 本地处理文件 简单快捷,下面直接放示例图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>批量上传并调整图片尺寸</title>
</head>
<style>
#previewContainer img {
width: 200px;
}
#downloadLinks a {
display: block;
}
</style>
<body>
<h1>上传图片</h1>
<h2>
<input placeholder="请输入宽度" value="300" oninput="widthInput()" id="myInput" type="number"/>
</h2>
<input type="file" id="imageUpload" multiple>
<button onclick="compressAndDownload()">压缩并下载</button>
<div id="previewContainer"></div>
<div id="downloadLinks"></div>
</body>
<script>
document.getElementById('imageUpload').addEventListener('change', handleFiles);
let html = ``
let widthValue = 300
let previewContainer = document.getElementById('previewContainer');
let downloadLinks = document.getElementById('downloadLinks');
function handleFiles(event) {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('image/')) {
displayPreview2(file);
}
}
}
function displayPreview2(file) {
const reader = new FileReader();
console.log(`文件对象哈`, file)
reader.onload = (e) => {
let str = `<img alt="${file.name}" src="${e.target.result}"/>`
html += str
previewContainer.innerHTML = html
};
reader.readAsDataURL(file);
}
function compressAndDownload() {
let compressedImages = [];
let nameList = []
previewContainer.querySelectorAll('img').forEach((img) => {
console.log(`获取到每个图片的信息哈`, img)
console.log(`获取到每个图片的信息哈2`, img.alt)
nameList.push(img.alt)
const canvas = document.createElement('canvas');
// canvas.width = 300;
canvas.width = widthValue
canvas.height = img.naturalHeight * (widthValue / img.naturalWidth);
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
compressedImages.push(canvas.toDataURL());
});
compressedImages.forEach((dataURL, index) => {
let a = document.createElement('a');
a.href = dataURL.replace('data:image/jpeg;base64,', '');
a.download = `${nameList[index]}`;
a.textContent = `${nameList[index]}`;
downloadLinks.appendChild(a);
});
}
// 宽度变化
function widthInput() {
let myInput = document.querySelector('#myInput')
widthValue = myInput.value
console.log(`输入宽度变化`, myInput.value)
}
</script>
</html>
完事,直接把html复制下来就能用,完结