我的知识记录

上传图片修改大小宽高(图文)

上传图片时修改大小宽高的方法有多种,以下是完整的解决方案:

1. 前端JavaScript处理(推荐)

HTML基础结构


 
html
<!DOCTYPE html> <html> <head> <title>图片上传尺寸调整</title> </head> <body> <div class="upload-container"> <h2>上传并调整图片尺寸</h2> <input type="file" id="imageInput" accept="image/*"> <div> <label>宽度: <input type="number" id="widthInput" value="800"></label> <label>高度: <input type="number" id="heightInput" value="600"></label> </div> <button id="uploadBtn">上传图片</button> <div id="preview"></div> </div> <script> // JavaScript代码见下方 </script> </body> </html>

JavaScript核心处理代码


 
javascript
document.getElementById('imageInput').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { previewImage(file); } }); function previewImage(file) { const reader = new FileReader(); reader.onload = function(event) { const img = new Image(); img.onload = function() { const preview = document.getElementById('preview'); preview.innerHTML = ` <div> <h3>原图预览:</h3> <img src="${event.target.result}" style="max-width: 300px; max-height: 200px;"> <p>原图尺寸: ${img.width} x ${img.height}</p> </div> `; }; img.src = event.target.result; }; reader.readAsDataURL(file); } document.getElementById('uploadBtn').addEventListener('click', async function() { const fileInput = document.getElementById('imageInput'); const width = parseInt(document.getElementById('widthInput').value); const height = parseInt(document.getElementById('heightInput').value); if (!fileInput.files[0]) { alert('请先选择图片文件'); return; } const originalFile = fileInput.files[0]; const resizedImage = await resizeImage(originalFile, width, height); await uploadImage(resizedImage); }); function resizeImage(file, targetWidth, targetHeight) { return new Promise((resolve) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { // 设置画布尺寸 canvas.width = targetWidth; canvas.height = targetHeight; // 绘制调整后的图像 ctx.drawImage(img, 0, 0, targetWidth, targetHeight); // 转换为Blob对象 canvas.toBlob(resolve, 'image/jpeg', 0.8); // 0.8是图片质量 }; img.src = URL.createObjectURL(file); }); } async function uploadImage(file) { const formData = new FormData(); formData.append('image', file, 'resized-image.jpg'); try { const response = await fetch('/upload', { method: 'POST', body: formData }); if (response.ok) { const result = await response.json(); alert('图片上传成功!'); console.log('上传结果:', result); } else { alert('上传失败'); } } catch (error) { console.error('上传错误:', error); alert('上传过程中发生错误'); } }

2. 保持宽高比的版本


 
javascript
function resizeImageKeepAspectRatio(file, maxWidth, maxHeight) { return new Promise((resolve) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { // 计算保持宽高比的新尺寸 let { width, height } = img; // 按比例缩放 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); // 转换为Blob对象 canvas.toBlob(resolve, 'image/jpeg', 0.8); }; img.src = URL.createObjectURL(file); }); }

3. 后端处理方案(Node.js)

Express.js后端示例


 
javascript
const express = require('express'); const multer = require('multer'); const sharp = require('sharp'); const path = require('path'); const app = express(); // 配置multer存储 const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); }, filename: function (req, file, cb) { cb(null, Date.now() + '-' + file.originalname); } }); const upload = multer({ storage: storage, limits: { fileSize: 10 * 1024 * 1024 // 10MB限制 }, fileFilter: function (req, file, cb) { // 只允许图片文件 if (file.mimetype.startsWith('image/')) { cb(null, true); } else { cb(new Error('只允许上传图片文件')); } } }); app.use(express.static('public')); app.use('/uploads', express.static('uploads')); // 上传接口 app.post('/upload', upload.single('image'), async (req, res) => { try { if (!req.file) { return res.status(400).json({ error: '没有上传文件' }); } // 获取客户端传来的尺寸参数 const width = parseInt(req.body.width) || 800; const height = parseInt(req.body.height) || 600; // 构建输出文件路径 const outputFilename = `resized-${req.file.filename}`; const outputPath = path.join('uploads', outputFilename); // 使用sharp调整图片尺寸 await sharp(req.file.path) .resize(width, height, { fit: 'cover', // 裁剪适应指定尺寸 position: 'center' }) .jpeg({ quality: 80 }) .toFile(outputPath); res.json({ message: '图片上传并调整尺寸成功', original: req.file, resized: { filename: outputFilename, path: outputPath, width: width, height: height } }); } catch (error) { console.error('处理图片时出错:', error); res.status(500).json({ error: '处理图片时出错' }); } }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });

4. Python后端处理


 
python
from flask import Flask, request, jsonify from PIL import Image import os from werkzeug.utils import secure_filename app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads' app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB限制 # 确保上传目录存在 os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) @app.route('/upload', methods=['POST']) def upload_image(): try: # 检查是否有文件上传 if 'image' not in request.files: return jsonify({'error': '没有图片文件'}), 400 file = request.files['image'] if file.filename == '': return jsonify({'error': '未选择文件'}), 400 # 检查文件类型 if not allowed_file(file.filename): return jsonify({'error': '不支持的文件类型'}), 400 # 保存原始文件 filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) # 获取尺寸参数 width = int(request.form.get('width', 800)) height = int(request.form.get('height', 600)) # 调整图片尺寸 resized_filename = f'resized_{filename}' resized_filepath = os.path.join(app.config['UPLOAD_FOLDER'], resized_filename) with Image.open(filepath) as img: # 调整尺寸 resized_img = img.resize((width, height), Image.Resampling.LANCZOS) resized_img.save(resized_filepath, optimize=True, quality=80) return jsonify({ 'message': '图片上传并调整尺寸成功', 'original_file': filename, 'resized_file': resized_filename, 'dimensions': { 'width': width, 'height': height } }) except Exception as e: return jsonify({'error': str(e)}), 500 def allowed_file(filename): ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS if __name__ == '__main__': app.run(debug=True)

5. 完整的HTML页面示例


 
html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>图片上传尺寸调整</title> <style> .container { max-width: 600px; margin: 50px auto; padding: 20px; font-family: Arial, sans-serif; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; } input[type="file"], input[type="number"] { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; } button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background-color: #0056b3; } #preview img { max-width: 100%; height: auto; border: 1px solid #ddd; border-radius: 4px; } .status { margin-top: 15px; padding: 10px; border-radius: 4px; } .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; } .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; } </style> </head> <body> <div class="container"> <h1>图片上传尺寸调整</h1> <div class="form-group"> <label for="imageInput">选择图片:</label> <input type="file" id="imageInput" accept="image/*"> </div> <div class="form-group"> <label for="widthInput">宽度 (像素):</label> <input type="number" id="widthInput" value="800" min="1"> </div> <div class="form-group"> <label for="heightInput">高度 (像素):</label> <input type="number" id="heightInput" value="600" min="1"> </div> <button id="uploadBtn">上传并调整尺寸</button> <div id="preview"></div> <div id="status"></div> </div> <script> document.getElementById('imageInput').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { previewImage(file); } }); function previewImage(file) { const reader = new FileReader(); reader.onload = function(event) { const img = new Image(); img.onload = function() { const preview = document.getElementById('preview'); preview.innerHTML = ` <h3>原图预览:</h3> <img src="${event.target.result}" style="max-width: 300px; max-height: 200px;"> <p>原图尺寸: ${img.width} x ${img.height}</p> `; }; img.src = event.target.result; }; reader.readAsDataURL(file); } document.getElementById('uploadBtn').addEventListener('click', async function() { const fileInput = document.getElementById('imageInput'); const width = parseInt(document.getElementById('widthInput').value); const height = parseInt(document.getElementById('heightInput').value); const statusDiv = document.getElementById('status'); // 清空状态信息 statusDiv.innerHTML = ''; if (!fileInput.files[0]) { showStatus('请先选择图片文件', 'error'); return; } if (width <= 0 || height <= 0) { showStatus('请输入有效的宽高值', 'error'); return; } try { showStatus('正在处理图片...', 'info'); const originalFile = fileInput.files[0]; const resizedImage = await resizeImage(originalFile, width, height); await uploadImage(resizedImage, width, height); } catch (error) { showStatus('处理过程中出现错误: ' + error.message, 'error'); } }); function resizeImage(file, targetWidth, targetHeight) { return new Promise((resolve) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { canvas.width = targetWidth; canvas.height = targetHeight; ctx.drawImage(img, 0, 0, targetWidth, targetHeight); canvas.toBlob(resolve, 'image/jpeg', 0.8); }; img.src = URL.createObjectURL(file); }); } async function uploadImage(file, width, height) { const formData = new FormData(); formData.append('image', file, 'resized-image.jpg'); formData.append('width', width); formData.append('height', height); try { const response = await fetch('/upload', { method: 'POST', body: formData }); if (response.ok) { const result = await response.json(); showStatus(`图片上传成功!调整后尺寸: ${width} x ${height}`, 'success'); } else { const error = await response.json(); showStatus('上传失败: ' + error.error, 'error'); } } catch (error) { showStatus('上传过程中发生错误: ' + error.message, 'error'); } } function showStatus(message, type) { const statusDiv = document.getElementById('status'); statusDiv.className = 'status ' + type; statusDiv.textContent = message; } </script> </body> </html>

主要特点

  1. 前端预览: 上传前可预览原图
  2. 自定义尺寸: 用户可输入目标宽高
  3. 保持质量: 使用适当的压缩算法保持图片质量
  4. 错误处理: 完善的错误提示和处理机制
  5. 响应式设计: 适配不同屏幕尺寸
你可以根据具体需求选择前端处理或后端处理方案,或者两者结合使用。前端处理可以减少服务器压力,而后端处理可以确保处理效果的一致性。
 

上传图片修改大小宽高(图文)

标签:

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

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

下一篇:如何修改文件属性时间(图文)