```jsx import React, { useState, useRef, useEffect } from 'react'; export default function App() { // State for the uploaded image const [image, setImage] = useState(null); const [previewUrl, setPreviewUrl] = useState(null); const [originalSize, setOriginalSize] = useState({ width: 0, height: 0 }); // State for image processing settings const [width, setWidth] = useState(800); const [height, setHeight] = useState(600); const [quality, setQuality] = useState(85); const [aspectRatio, setAspectRatio] = useState('original'); const [format, setFormat] = useState('original'); const [autoAdjust, setAutoAdjust] = useState(true); // State for UI feedback const [isProcessing, setIsProcessing] = useState(false); const [error, setError] = useState(null); const [successMessage, setSuccessMessage] = useState(null); const [isDragging, setIsDragging] = useState(false); // Refs const canvasRef = useRef(null); const imageRef = useRef(null); const fileInputRef = useRef(null); // Handle image upload const handleImageUpload = (e) => { const file = e.target.files?.[0] || e.dataTransfer?.files?.[0]; if (file) { // Check if it's an image file if (!file.type.startsWith('image/')) { setError('Please upload a valid image file'); return; } setError(null); // Create a preview URL for immediate display const reader = new FileReader(); reader.onload = (event) => { setPreviewUrl(event.target.result); setImage(file); // Get original image dimensions const img = new Image(); img.onload = () => { setOriginalSize({ width: img.width, height: img.height }); setWidth(img.width); setHeight(img.height); }; img.src = event.target.result; }; reader.readAsDataURL(file); } }; // Handle drag over const handleDragOver = (e) => { e.preventDefault(); setIsDragging(true); }; // Handle drag leave const handleDragLeave = () => { setIsDragging(false); }; // Handle drop const handleDrop = (e) => { e.preventDefault(); setIsDragging(false); handleImageUpload(e); }; // Handle image processing const processImage = () => { if (!image) return; setIsProcessing(true); setError(null); setSuccessMessage(null); // Create a new image element const img = new Image(); img.src = previewUrl; img.onload = () => { // Calculate dimensions based on aspect ratio let calculatedWidth = width; let calculatedHeight = height; if (aspectRatio !== 'original') { const ratio = aspectRatio.split(':').map(Number); if (ratio.length === 2 && ratio[0] > 0 && ratio[1] > 0) { const targetRatio = ratio[0] / ratio[1]; if (autoAdjust) { if (img.width / img.height > targetRatio) { calculatedHeight = Math.round(img.width / targetRatio); calculatedWidth = img.width; } else { calculatedWidth = Math.round(img.height * targetRatio); calculatedHeight = img.height; } } else { // Keep specified dimensions but maintain aspect ratio if (calculatedWidth / calculatedHeight > targetRatio) { calculatedHeight = Math.round(calculatedWidth / targetRatio); } else { calculatedWidth = Math.round(calculatedHeight * targetRatio); } } } } // Create canvas for processing const canvas = canvasRef.current; const ctx = canvas.getContext('2d'); canvas.width = calculatedWidth; canvas.height = calculatedHeight; // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw image on canvas with resizing ctx.drawImage(img, 0, 0, calculatedWidth, calculatedHeight); // Get the processed image data URL let mimeType = 'image/jpeg'; if (format === 'png') { mimeType = 'image/png'; } else if (format === 'webp') { mimeType = 'image/webp'; } // Adjust quality only for JPEG and WebP let imageDataUrl = canvas.toDataURL(mimeType, format === 'original' ? undefined : quality / 100); // Update the preview with processed image setPreviewUrl(imageDataUrl); // Show success message setSuccessMessage('Image processed successfully!'); setIsProcessing(false); }; img.onerror = () => { setError('Failed to load image'); setIsProcessing(false); }; }; // Handle image download const handleDownload = () => { if (!previewUrl) return; // Create a link element const link = document.createElement('a'); link.href = previewUrl; const ext = format === 'original' ? image.type.split('/').pop() : format; link.download = `resized-image-${new Date().getTime()}.${ext}`; // Append link to body and click it document.body.appendChild(link); link.click(); // Remove link from DOM document.body.removeChild(link); // Show success message setSuccessMessage('Image downloaded successfully!'); }; // Reset all settings const resetSettings = () => { setWidth(originalSize.width || 800); setHeight(originalSize.height || 600); setQuality(85); setAspectRatio('original'); setFormat('original'); setAutoAdjust(true); // Reset preview to original image if (image) { setPreviewUrl(URL.createObjectURL(image)); } setSuccessMessage('Settings reset to defaults'); }; // Handle aspect ratio selection const handleAspectRatioChange = (ratio) => { setAspectRatio(ratio); if (ratio === 'original') { setWidth(originalSize.width); setHeight(originalSize.height); } else { const [w, h] = ratio.split(':').map(Number); if (w && h) { const newWidth = Math.min(originalSize.width, 1200); const newHeight = Math.round(newWidth * h / w); setWidth(newWidth); setHeight(newHeight); } } }; // Effect to handle keyboard shortcuts useEffect(() => { const handleKeyDown = (e) => { // Ctrl/Cmd + Enter to process image if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { if (!isProcessing && image) { processImage(); } } // Ctrl/Cmd + S to download if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); if (previewUrl) { handleDownload(); } } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, [isProcessing, image, previewUrl]); return (

Image Resizer

Resize, convert, and download images in any format

{/* Upload Section */}
{/* Image Preview */} {previewUrl && (
Preview {isProcessing && (
)} {originalSize.width && originalSize.height && (
Original: {originalSize.width}×{originalSize.height}px Current: {width}×{height}px
)}
)} {/* Settings Section */} {image && (

Resize Settings

{/* Width & Height */}
{ const newValue = parseInt(e.target.value) || 1; setWidth(newValue); if (autoAdjust && aspectRatio !== 'original') { const [w, h] = aspectRatio.split(':').map(Number); if (w && h) { setHeight(Math.round(newValue * h / w)); } } }} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
{ const newValue = parseInt(e.target.value) || 1; setHeight(newValue); if (autoAdjust && aspectRatio !== 'original') { const [w, h] = aspectRatio.split(':').map(Number); if (w && h) { setWidth(Math.round(newValue * w / h)); } } }} className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" />
setAutoAdjust(e.target.checked)} className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded" />
{/* Quality */}
setQuality(parseInt(e.target.value))} className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer" /> {quality}%

Lower values reduce file size but may affect quality

{/* Aspect Ratio */}
{[ { value: 'original', label: 'Original' }, { value: '1:1', label: '1:1' }, { value: '4:3', label: '4:3' }, { value: '3:4', label: '3:4' }, { value: '16:9', label: '16:9' }, { value: '9:16', label: '9:16' }, { value: '2:3', label: '2:3' }, { value: '3:2', label: '3:2' } ].map(({ value, label }) => ( ))}
{/* Format */}
{[ { value: 'original', label: 'Original' }, { value: 'jpg', label: 'JPG' }, { value: 'png', label: 'PNG' }, { value: 'webp', label: 'WEBP' } ].map(({ value, label }) => ( ))}

Choose output format for your image

{/* Action Buttons */}

Keyboard shortcuts: Ctrl+Enter to process, Ctrl+S to download

)} {/* Download Section */} {previewUrl && (

Download Your Image

Your processed image is ready to download. The file will be saved with your chosen settings.

)} {/* Error and Success Messages */} {error && (
{error}
)} {successMessage && (
{successMessage}
)}
{/* Instructions */}

How to Use

1. Upload an image by clicking the "Click to upload" area or dragging an image file.

2. Adjust the resize settings according to your needs:

  • Set custom width and height in pixels
  • Adjust the quality slider (lower values reduce file size)
  • Select an aspect ratio to maintain proportions
  • Choose a format to convert your image to

3. Click "Resize Image" to apply your settings and preview the result.

4. Click "Download Image" to save your processed image.

{/* Hidden canvas element for image processing */}
); } ```