Prompt
How do I automatically resize images when users upload them?
Latest observation
Nov 3, 2026
OpenAI APIWeb search: off
To automatically resize images on upload, you typically do it in one of three places:
- In the browser before upload
- On your backend after upload
- In a storage/CDN pipeline (if you use cloud services)
Common approach: resize on the backend
This is the most reliable option because you control the image size regardless of what the user uploads.
Typical flow
- User uploads image
- Server receives the file
- Server checks file type/size
- Server resizes the image to one or more target dimensions
- Server saves the resized versions
- Optional: keep the original too
Example in Node.js using Sharp
const sharp = require('sharp');
const fs = require('fs');
async function resizeImage(inputPath, outputPath) {
await sharp(inputPath)
.resize(800, 800, {
fit: 'inside',
withoutEnlargement: true
})
.toFile(outputPath);
}
This resizes the image so it fits within 800x800 while preserving aspect ratio.
If you want to resize before upload in the browser
This reduces upload bandwidth, which is useful for mobile users.
Example in JavaScript
async function resizeImage(file, maxWidth, maxHeight) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
const scale = Math.min(maxWidth / width, maxHeight / height, 1);
width = Math.round(width * scale);
height = Math.round(height * scale);
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => resolve(blob), 'image/jpeg', 0.9);
};
img.src = URL.createObjectURL(file);
});
}
Best practices
- Preserve aspect ratio
- Use a modern image library like Sharp, Pillow, or ImageMagick
- Validate file types
- Strip metadata if needed for privacy
- Generate multiple sizes if you need thumbnails and full-size images
- Consider async processing for large uploads
Recommended stack examples
- Node.js: Sharp
- Python: Pillow
- PHP: Intervention Image / GD
- Java: Thumbnailator / ImgScalr
If you tell me your backend language/framework, I can give you a ready-to-use example.