2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Image compression plays a vital role in many application scenarios, especially when uploading images on the client side. Original images are often large in size. Direct uploading not only consumes a lot of bandwidth resources, but may also result in slow upload speeds, seriously affecting user experience. Therefore, compressing images before uploading them to the server has become a key optimization measure. Through compression, the image file size is significantly reduced, thereby speeding up upload speeds, improving efficiency, and ensuring that users have a smooth and unimpeded experience. This optimization is particularly important under poor network conditions.
In short, image compression can effectively solve the bandwidth pressure and time cost problems caused by uploading large files, and is an effective means to improve application response speed and enhance user satisfaction. It processes images intelligently, removes redundant data, and significantly reduces file size while maintaining visual quality as much as possible, making the image upload process faster and more efficient, thereby optimizing the performance of the entire application.
<!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.7.1/jquery.min.js"></script>
<style>
div {
text-align: center;
}
input {
height: 50px;
line-height: 50px;
}
</style>
</head>
<body>
<input id="file" type="file" accept="image/*">
<div>压缩前的图片大小:<span id="beforeSize"></span>
<p><img id="before" /></p>
</div>
<div>压缩后的图片大小:<span id="afterSize"></span>
<p>
<img id="after" />
</p>
</div>
<script>
$("#file").change(function () {
const file = this.files[0];
$("#before").attr("src", URL.createObjectURL(file));
$("#before").css({
width: '500',
height: 'auto'
});
const fileSize = file.size / 1024;
$("#beforeSize").html(fileSize.toFixed(2) + " KB");
if (!file) return;
compressImage(file, 1, 0.7).then(base64 => {
$("#after").attr("src", base64);
$("#after").css({
width: '500',
height: 'auto'
});
const sizeInKB = (base64.length * 3 / 4) / 1024;
$("#afterSize").html(sizeInKB.toFixed(2) + " KB");
});
});
function compressImage(file, maxWidth, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function (e) {
const img = new Image();
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL('image/jpeg', quality || 0.9));
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
</script>
</body>
</html>