如何在JS中调整用户上传图片尺寸?生成指定规格缩略图及大图
To generate the required 136×136 thumbnails and 454×527 images, we'll use the HTML5 Canvas API to resize images client-side before sending them to your server for database storage. Here's how to modify your existing code:
Step 1: Add a Resize Helper Function
First, create a reusable function to handle image resizing. This function takes the original image, target dimensions, and a callback to return the resized image as a Blob (ideal for file uploads):
function resizeImage(originalImg, targetWidth, targetHeight, callback) { const canvas = document.createElement('canvas'); canvas.width = targetWidth; canvas.height = targetHeight; const ctx = canvas.getContext('2d'); // Draw the image onto the canvas, stretching to fit the target dimensions ctx.drawImage(originalImg, 0, 0, targetWidth, targetHeight); // Convert canvas to a JPEG Blob (adjust quality from 0.0 to 1.0 as needed) canvas.toBlob(function(resizedBlob) { callback(resizedBlob); }, 'image/jpeg', 0.9); }
Step 2: Modify the File Upload Handling
Update your existing code to process each uploaded image, generate both resized versions, and prepare them for upload to your server:
const fileInput = document.getElementById('your-file-input-id'); // Replace with your input ID fileInput.addEventListener('change', function() { const files = fileInput.files; for (let i = 0; i < files.length; i++) { const file = files[i]; const imageType = /image.*/; if (!file.type.match(imageType)) { console.log('Skipping non-image file:', file.name); continue; } const reader = new FileReader(); reader.onload = function(e) { // Create an image element to load the original file data const originalImg = new Image(); originalImg.src = e.target.result; originalImg.onload = function() { // Generate 136x136 thumbnail resizeImage(originalImg, 136, 136, function(thumbnailBlob) { // Generate 454x527 image resizeImage(originalImg, 454, 527, function(largeImageBlob) { // Now send both blobs to your server for database storage uploadResizedImages(thumbnailBlob, largeImageBlob, file.name); }); }); // Optional: Update the preview image with the thumbnail const previewImg = document.getElementById('thumbnil'); previewImg.src = URL.createObjectURL(thumbnailBlob); }; }; reader.readAsDataURL(file); } });
Step 3: Add the Upload Function
Create a function to send the resized images to your server using FormData (this is standard for file uploads):
function uploadResizedImages(thumbnailBlob, largeImageBlob, originalFileName) { const formData = new FormData(); // Append the resized images with descriptive names formData.append('thumbnail', thumbnailBlob, `${originalFileName}_thumb.jpg`); formData.append('largeImage', largeImageBlob, `${originalFileName}_large.jpg`); // Send the data to your server endpoint (replace with your actual URL) fetch('/api/upload-images', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error('Upload failed'); } return response.json(); }) .then(data => { console.log('Images successfully stored in database:', data); // Handle success (e.g., show a message to the user) }) .catch(error => { console.error('Error uploading images:', error); // Handle error (e.g., show an error message) }); }
Notes on Aspect Ratio (Optional)
If you want to maintain the original image's aspect ratio instead of stretching it to fit the exact dimensions, you can adjust the resizeImage function to calculate the correct draw dimensions. For example, to fit the image within the target size without stretching:
function resizeImageMaintainAspect(originalImg, maxWidth, maxHeight, callback) { let width = originalImg.width; let height = originalImg.height; // Calculate scaling factor to fit within target dimensions const scaleFactor = Math.min(maxWidth / width, maxHeight / height); width *= scaleFactor; height *= scaleFactor; const canvas = document.createElement('canvas'); canvas.width = maxWidth; canvas.height = maxHeight; const ctx = canvas.getContext('2d'); // Center the image on the canvas const xOffset = (maxWidth - width) / 2; const yOffset = (maxHeight - height) / 2; ctx.drawImage(originalImg, xOffset, yOffset, width, height); canvas.toBlob(function(resizedBlob) { callback(resizedBlob); }, 'image/jpeg', 0.9); }
Use this function instead if you need to preserve the image's proportions.
内容的提问来源于stack exchange,提问作者jone2

