我的知识记录

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

修改上传图片的大小尺寸有多种方法,以下是常用的几种方式:

1. 使用图像编辑软件

桌面软件

  • Photoshop: 图像 → 图像大小 → 输入新尺寸
  • GIMP: 图像 → 缩放图像
  • Paint.NET: 图像 → 调整大小
  • IrfanView: 图像 → 调整大小/裁剪

在线工具

  • TinyPNG
  • Photopea (在线Photoshop替代品)
  • Canva
  • ResizeImage.net

2. 编程方式调整图片尺寸

Python (使用Pillow库)


 
python
from PIL import Image def resize_image(input_path, output_path, size): """ 调整图片尺寸 :param input_path: 输入图片路径 :param output_path: 输出图片路径 :param size: 新尺寸 (width, height) """ with Image.open(input_path) as img: # 方法1: 直接调整到指定尺寸(可能变形) resized_img = img.resize(size) # 方法2: 保持宽高比调整 img.thumbnail(size, Image.Resampling.LANCZOS) resized_img = img # 方法3: 按比例缩放 # percent = 0.5 # 缩放到50% # width, height = img.size # new_size = (int(width * percent), int(height * percent)) # resized_img = img.resize(new_size, Image.Resampling.LANCZOS) resized_img.save(output_path) # 使用示例 resize_image('input.jpg', 'output.jpg', (800, 600))

JavaScript (前端)


 
javascript
function resizeImage(file, maxWidth, maxHeight) { return new Promise((resolve) => { const img = new Image(); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); img.onload = function() { // 计算新尺寸保持宽高比 let { width, height } = img; if (width > height) { if (width > maxWidth) { height = (height * maxWidth) / width; width = maxWidth; } } else { if (height > maxHeight) { width = (width * maxHeight) / height; height = maxHeight; } } canvas.width = width; canvas.height = height; // 绘制调整后的图像 ctx.drawImage(img, 0, 0, width, height); // 转换为Blob对象 canvas.toBlob(resolve, 'image/jpeg', 0.8); }; img.src = URL.createObjectURL(file); }); } // 使用示例 document.getElementById('fileInput').addEventListener('change', async function(e) { const file = e.target.files[0]; const resizedBlob = await resizeImage(file, 800, 600); // 使用resizedBlob进行上传 });

Node.js (使用Sharp库)


 
javascript
const sharp = require('sharp'); async function resizeImage(inputPath, outputPath, width, height) { try { await sharp(inputPath) .resize(width, height, { fit: 'inside', // 保持宽高比 withoutEnlargement: true // 不放大图片 }) .jpeg({ quality: 80 }) // 设置质量 .toFile(outputPath); console.log('图片调整完成'); } catch (error) { console.error('调整图片出错:', error); } } // 使用示例 resizeImage('input.jpg', 'output.jpg', 800, 600);

3. 在上传过程中自动调整尺寸

前端自动压缩上传


 
html
<input type="file" id="imageUpload" accept="image/*"> <script> document.getElementById('imageUpload').addEventListener('change', async function(e) { const file = e.target.files[0]; if (!file) return; // 检查文件类型 if (!file.type.match('image.*')) { alert('请选择图片文件'); return; } // 压缩图片 const compressedFile = await compressImage(file, 800, 600, 0.8); // 上传压缩后的图片 uploadImage(compressedFile); }); function compressImage(file, maxWidth, maxHeight, quality) { return new Promise((resolve) => { 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.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, width, height); canvas.toBlob(resolve, 'image/jpeg', quality); }; img.src = URL.createObjectURL(file); }); } function uploadImage(file) { const formData = new FormData(); formData.append('image', file, 'resized-image.jpg'); fetch('/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log('上传成功:', data)) .catch(error => console.error('上传失败:', error)); } </script>

后端处理上传的图片


 
python
from flask import Flask, request, jsonify from PIL import Image import os from werkzeug.utils import secure_filename app = Flask(__name__) UPLOAD_FOLDER = 'uploads' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif'} @app.route('/upload', methods=['POST']) def upload_file(): if 'image' not in request.files: return jsonify({'error': '没有图片文件'}), 400 file = request.files['image'] if file.filename == '': return jsonify({'error': '未选择文件'}), 400 if file and allowed_file(file.filename): filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) # 调整图片尺寸 resize_image(filepath, filepath, (800, 600)) return jsonify({'message': '上传成功', 'filename': filename}) return jsonify({'error': '不支持的文件类型'}), 400 def resize_image(input_path, output_path, size): with Image.open(input_path) as img: img.thumbnail(size, Image.Resampling.LANCZOS) img.save(output_path, optimize=True, quality=80)

4. 命令行工具

使用ImageMagick


 
bash
# 调整图片尺寸 convert input.jpg -resize 800x600 output.jpg # 按百分比缩放 convert input.jpg -resize 50% output.jpg # 保持宽高比并限制最大尺寸 convert input.jpg -resize "800x600>" output.jpg

使用FFmpeg


 
bash
# 调整图片尺寸 ffmpeg -i input.jpg -vf scale=800:600 output.jpg

5. 移动端解决方案

Android (Java/Kotlin)


 
java
// 使用BitmapFactory调整图片尺寸 public Bitmap resizeBitmap(String imagePath, int maxWidth, int maxHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int sampleSize = calculateSampleSize(options, maxWidth, maxHeight); options.inJustDecodeBounds = false; options.inSampleSize = sampleSize; Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); // 进一步调整尺寸 return Bitmap.createScaledBitmap(bitmap, maxWidth, maxHeight, true); }

iOS (Swift)


 
swift
// 调整UIImage尺寸 func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / size.width let heightRatio = targetSize.height / size.height let newSize = widthRatio > heightRatio ? CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio, height: size.height * widthRatio) let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage ?? image }

注意事项

  1. 保持宽高比: 避免图片变形,建议保持原始宽高比
  2. 质量控制: 压缩时注意图片质量,避免过度压缩导致失真
  3. 文件格式: 根据需要选择合适的输出格式(JPEG、PNG等)
  4. 性能考虑: 大图处理可能消耗较多内存和CPU资源
  5. 浏览器兼容性: 前端处理时注意不同浏览器的支持情况
你希望在哪个环节调整图片尺寸?是在上传前手动调整,还是在上传过程中自动处理?
 

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

标签:

更新时间:2025-12-15 14:29:18

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

下一篇:上传图片修改大小宽高(图文)