Base64 是一种常见的编码格式,用于将二进制数据转换为 ASCII 字符串。在 JavaScript 中,可以使用 btoa
和 atob
函数进行 Base64 编码和解码。然而,Base64 编码本身并不是一种压缩算法,它只是将二进制数据转换为可打印的 ASCII 字符串。因此,如果你想要压缩图片,应该使用其他压缩算法,如 JPEG 或 PNG 压缩。
以下是一个使用 JavaScript 和 Canvas API 将图片转换为 Base64 编码并进行压缩的示例:
以下是一个将图片转换为 Base64 编码并进行压缩的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Compression</title>
</head>
<body>
<input type="file" id="imageInput" accept="image/*">
<img id="preview" alt="Preview">
<script>
document.getElementById('imageInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
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');
const maxWidth = 800; // 设置最大宽度
const maxHeight = 600; // 设置最大高度
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
const quality = 0.7; // 设置压缩质量
const base64 = canvas.toDataURL('image/jpeg', quality);
document.getElementById('preview').src = base64;
console.log(base64);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
<input type="file">
选择图片文件。FileReader
读取文件内容。canvas.toDataURL
方法将图片转换为 Base64 编码,并设置压缩质量。quality
参数,通常在 0 到 1 之间。通过这种方式,你可以在客户端对图片进行压缩并转换为 Base64 编码,从而减小文件大小并提高加载速度。
领取专属 10元无门槛券
手把手带您无忧上云