js通过canvas进行图片压缩

本文将介绍如何利用HTML5的Canvas API进行图片压缩。通过读取图片,将其绘制到Canvas上,再导出为新的压缩图片,可以有效地减小图片文件大小,适用于前端开发中的图片上传和优化场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!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 => {
					// const formData = new FormData()
					// formData.append('file', file, file.name)
					let alink = document.createElement('a')
					alink.href = URL.createObjectURL(file)
					alink.download = file.name
					alink.click()
				})
			}
			// 压缩图片
			compressImage = (file, success) => {
			    // 图片小于1M不压缩
			    // if (file.size < Math.pow(1024, 2)) {
			    //     return success(file);
			    // }
			    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;  // 默认图片质量为0.92
			            // 生成canvas
			            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);
			
			            // 铺底色 PNG转JPEG时透明区域会变黑色
			            ctx.fillStyle = "#fff";
			            ctx.fillRect(0, 0, w, h);
			
			            ctx.drawImage(img, 0, 0, w, h);
			            // quality值越小,所绘制出的图像越模糊
			            const base64 = canvas.toDataURL('image/jpeg', quality); // 图片格式jpeg或webp可以选0-1质量区间
			
			            // 返回base64转blob的值
			            console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`);
			            // 去掉url的头,并转换为byte
			            const bytes = window.atob(base64.split(',')[1]);
			            // 处理异常,将ascii码小于0的转换为大于0
			            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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值