javascript图片大小处理函数
封面图
•
2025-10-17
•
JavaScript
154
0
0
0
在 JavaScript 中处理图片大小(如缩放、裁剪、调整尺寸等)通常需要使用 `<canvas>` 元素来操作图像数据。以下是一个简单的图片大小处理函数示例,可以用于 **缩放图片** 到指定宽度和高度。 --- ## ✅ 示例:JavaScript 图片缩放函数 ```javascript function resizeImage(file, maxWidth, maxHeight, callback) { const reader = new FileReader(); reader.onload = function(event) { const img = new Image(); img.onload = function() { 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 并绘制图片 const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // 将 canvas 转换为 Blob 或 Data URL canvas.toBlob(function(blob) { callback(blob); }, 'image/jpeg', 0.8); // 可以调整压缩质量(0.8 是默认) }; img.src = event.target.result; }; reader.readAsDataURL(file); } ``` --- ## 🔧 使用示例 ```html <input type="file" id="imageInput" accept="image/*"> <script> document.getElementById('imageInput').addEventListener('change', function(e) { const file = e.target.files[0]; if (!file) return; resizeImage(file, 800, 600, function(blob) { // 这里你可以将 blob 发送到服务器或生成预览 const preview = document.createElement('img'); preview.src = URL.createObjectURL(blob); document.body.appendChild(preview); }); }); </script> ``` --- ## 📌 可选功能扩展 ### 1. **图片裁剪** 可以通过 `ctx.drawImage()` 的参数控制裁剪区域。 ```javascript ctx.drawImage(img, x, y, width, height, 0, 0, canvas.width, canvas.height); ``` ### 2. **旋转图片** 使用 `ctx.rotate()` 方法实现。 ### 3. **调整质量** 通过 `canvas.toBlob(..., 'image/jpeg', quality)` 设置压缩质量(0~1)。 --- ## 📦 如果你需要更强大的图片处理库 - [Fabric.js](http://fabricjs.com/) - [Jimp](https://github.com/oliver-moran/jimp)(Node.js 环境下使用) - [Cropper.js](https://github.com/fengyuanchen/cropperjs) --- 如果你有特定需求(比如裁剪、旋转、格式转换等),可以告诉我,我可以帮你写更具体的代码。
上一篇:
用javascript检查checkbox复选框至少选择一项
下一篇:
jquery不间断滚动图片效果
标题录入,一次不能超过6条
返回顶部
留言
留言
评论