我的知识记录

如何修改上传图片大小(图文)

修改上传图片大小有多种方法,主要包括压缩图片尺寸和降低图片质量。以下是常用的实现方式:

1. 使用图像编辑软件

Photoshop

  1. 打开图片 → 图像 → 图像大小
  2. 调整宽度/高度像素值
  3. 保持约束比例
  4. 选择适当的重采样方法
  5. 保存优化后的图片

GIMP (免费替代方案)

  1. 打开图片 → 图像 → 缩放图像
  2. 设置新尺寸
  3. 导出为 → 选择JPEG质量

2. 在线图片压缩工具


 
html
<!-- 常用在线工具 --> <!-- 1. TinyPNG (tinypng.com) 2. CompressJPEG (compressjpeg.com) 3. ImageOptim (imageoptim.com) 4. Squoosh (squoosh.app) -->

3. 编程方式修改图片大小

Python + PIL/Pillow


 
python
from PIL import Image import os def resize_image(input_path, output_path, max_size=(800, 600), quality=85): """ 调整图片大小和质量 :param input_path: 输入图片路径 :param output_path: 输出图片路径 :param max_size: 最大尺寸 (宽度, 高度) :param quality: JPEG质量 (1-100) """ with Image.open(input_path) as img: # 计算新尺寸保持宽高比 img.thumbnail(max_size, Image.Resampling.LANCZOS) # 保存图片 if output_path.lower().endswith('.jpg') or output_path.lower().endswith('.jpeg'): img.save(output_path, 'JPEG', quality=quality, optimize=True) else: img.save(output_path, optimize=True) # 显示结果 original_size = os.path.getsize(input_path) new_size = os.path.getsize(output_path) print(f"原图大小: {original_size/1024:.1f}KB") print(f"压缩后大小: {new_size/1024:.1f}KB") print(f"压缩率: {(1-new_size/original_size)*100:.1f}%") # 使用示例 resize_image('original.jpg', 'compressed.jpg', (1024, 768), 80)

JavaScript (前端浏览器中处理)


 
javascript
function resizeImage(file, maxWidth, maxHeight, quality = 0.8) { return new Promise((resolve, reject) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { // 计算新尺寸 let width = img.width; let height = img.height; if (width > height) { if (width > maxWidth) { height = Math.round((height *= maxWidth / width)); width = maxWidth; } } else { if (height > maxHeight) { width = Math.round((width *= maxHeight / height)); height = maxHeight; } } // 设置canvas尺寸 canvas.width = width; canvas.height = height; // 绘制缩放后的图片 ctx.drawImage(img, 0, 0, width, height); // 转换为Blob canvas.toBlob(resolve, 'image/jpeg', quality); }; img.onerror = reject; img.src = URL.createObjectURL(file); }); } // 使用示例 async function handleImageUpload(event) { const file = event.target.files[0]; const resizedBlob = await resizeImage(file, 800, 600, 0.8); // 创建新的File对象用于上传 const resizedFile = new File([resizedBlob], 'resized_' + file.name, { type: 'image/jpeg' }); console.log('原始文件大小:', file.size); console.log('压缩后文件大小:', resizedFile.size); // 这里可以继续执行上传操作 // uploadFile(resizedFile); }

4. 命令行工具

ImageMagick


 
bash
# 安装ImageMagick后使用 # 调整尺寸 convert input.jpg -resize 800x600 output.jpg # 按百分比缩放 convert input.jpg -resize 50% output.jpg # 限制文件大小 convert input.jpg -define jpeg:extent=500KB output.jpg # 组合使用 convert input.jpg -resize 1024x768 -quality 80 output.jpg

ffmpeg


 
bash
# 调整图片尺寸 ffmpeg -i input.jpg -vf scale=800:600 output.jpg # 指定输出质量 ffmpeg -i input.jpg -q:v 2 output.jpg

5. 移动端处理

Android (Java/Kotlin)


 
java
// Java示例 public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float ratioBitmap = (float) width / (float) height; float ratioMax = (float) maxWidth / (float) maxHeight; int finalWidth = maxWidth; int finalHeight = maxHeight; if (ratioMax > ratioBitmap) { finalWidth = (int) ((float)maxHeight * ratioBitmap); } else { finalHeight = (int) ((float)maxWidth / ratioBitmap); } return Bitmap.createScaledBitmap(bitmap, finalWidth, finalHeight, true); }

6. 自动化批处理

Python批量处理


 
python
import os from PIL import Image def batch_resize_images(input_folder, output_folder, max_size=(800, 600), quality=85): """ 批量调整图片大小 """ if not os.path.exists(output_folder): os.makedirs(output_folder) supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff') for filename in os.listdir(input_folder): if filename.lower().endswith(supported_formats): input_path = os.path.join(input_folder, filename) output_path = os.path.join(output_folder, filename) try: with Image.open(input_path) as img: img.thumbnail(max_size, Image.Resampling.LANCZOS) if filename.lower().endswith(('.jpg', '.jpeg')): img.save(output_path, 'JPEG', quality=quality, optimize=True) else: img.save(output_path, optimize=True) print(f"处理完成: {filename}") except Exception as e: print(f"处理失败 {filename}: {e}") # 使用示例 batch_resize_images('./original_images', './compressed_images', (1024, 768), 80)

7. 上传前自动压缩

HTML5 + JavaScript 上传前处理


 
html
<!DOCTYPE html> <html> <head> <title>图片上传压缩</title> </head> <body> <input type="file" id="imageInput" accept="image/*" multiple> <div id="result"></div> <script> document.getElementById('imageInput').addEventListener('change', async function(e) { const files = Array.from(e.target.files); const resultDiv = document.getElementById('result'); for (let file of files) { if (!file.type.startsWith('image/')) continue; try { const compressedBlob = await compressImage(file, 800, 600, 0.8); const compressedFile = new File([compressedBlob], `compressed_${file.name}`, {type: 'image/jpeg'}); // 显示压缩效果 const info = ` <p>文件: ${file.name}</p> <p>原始大小: ${(file.size/1024).toFixed(1)} KB</p> <p>压缩后大小: ${(compressedFile.size/1024).toFixed(1)} KB</p> <p>压缩率: ${((1-compressedFile.size/file.size)*100).toFixed(1)}%</p> <hr> `; resultDiv.innerHTML += info; // 这里可以执行实际上传 // await uploadFile(compressedFile); } catch (error) { console.error('压缩失败:', error); } } }); function compressImage(file, maxWidth, maxHeight, quality) { return new Promise((resolve, reject) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { let width = img.width; let height = img.height; // 计算新尺寸保持比例 const ratio = Math.min(maxWidth/width, maxHeight/height); width = Math.floor(width * ratio); height = Math.floor(height * ratio); canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, width, height); canvas.toBlob(resolve, 'image/jpeg', quality); }; img.onerror = reject; img.src = URL.createObjectURL(file); }); } </script> </body> </html>

常见的图片尺寸建议

用途 推荐尺寸 文件大小
网页展示 800×600 ~ 1920×1080 100-500KB
社交媒体 1080×1080 (正方形) 200-800KB
电子邮件附件 640×480 50-200KB
移动端 750×1334 (手机屏幕) 100-300KB
选择合适的压缩参数可以在保持视觉质量的同时显著减小文件大小。
 

如何修改上传图片大小(图文)

标签:

更新时间:2025-12-15 14:13:34

上一篇:怎么修改上传到网络的时间(图文)

下一篇:网上上传文件更改上传时间(图文)