File size: 13,469 Bytes
ad8820e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | import React, { useState } from 'react';
import { Upload, Download, ArrowRight, X } from 'lucide-react';
interface UploadedImage {
id: string;
file: File;
preview: string;
name: string;
size: number;
originalFormat: string;
}
interface ConvertedImage {
id: string;
originalName: string;
originalFormat: string;
outputFormat: string;
preview: string;
size: number;
downloadCount: number;
}
const IMAGE_FORMATS = [
{ format: 'JPEG', extension: 'jpg', estimatedSize: '~45-65%' },
{ format: 'PNG', extension: 'png', estimatedSize: '~80-120%' },
{ format: 'WebP', extension: 'webp', estimatedSize: '~30-50%' },
{ format: 'GIF', extension: 'gif', estimatedSize: '~60-100%' },
{ format: 'BMP', extension: 'bmp', estimatedSize: '~150-200%' },
{ format: 'TIFF', extension: 'tiff', estimatedSize: '~100-150%' },
{ format: 'SVG', extension: 'svg', estimatedSize: '~10-30%' },
{ format: 'ICO', extension: 'ico', estimatedSize: '~5-15%' },
{ format: 'AVIF', extension: 'avif', estimatedSize: '~25-40%' },
{ format: 'HEIC', extension: 'heic', estimatedSize: '~35-55%' },
];
export default function ImageFormatConverter() {
const [uploadedImages, setUploadedImages] = useState<UploadedImage[]>([]);
const [selectedFormat, setSelectedFormat] = useState<string>('JPEG');
const [convertedImages, setConvertedImages] = useState<ConvertedImage[]>([]);
const [currentPage, setCurrentPage] = useState<'upload' | 'download'>('upload');
const [dragActive, setDragActive] = useState(false);
const handleDrag = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (e.type === 'dragenter' || e.type === 'dragover') {
setDragActive(true);
} else if (e.type === 'dragleave') {
setDragActive(false);
}
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setDragActive(false);
const files = Array.from(e.dataTransfer.files).filter((file) =>
file.type.startsWith('image/')
);
processFiles(files);
};
const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
processFiles(files);
};
const processFiles = (files: File[]) => {
files.forEach((file) => {
const reader = new FileReader();
reader.onload = (e) => {
const format = file.type.split('/')[1].toUpperCase();
const newImage: UploadedImage = {
id: Math.random().toString(36).substr(2, 9),
file,
preview: e.target?.result as string,
name: file.name,
size: file.size,
originalFormat: format,
};
setUploadedImages((prev) => [...prev, newImage]);
};
reader.readAsDataURL(file);
});
};
const removeImage = (id: string) => {
setUploadedImages((prev) => prev.filter((img) => img.id !== id));
};
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
};
const handleStartConversion = () => {
const converted = uploadedImages.map((img) => ({
id: img.id,
originalName: img.name.split('.')[0],
originalFormat: img.originalFormat,
outputFormat: selectedFormat,
preview: img.preview,
size: Math.round(img.size * (Math.random() * 0.5 + 0.5)),
downloadCount: 0,
}));
setConvertedImages(converted);
setCurrentPage('download');
};
const getDownloadFilename = (image: ConvertedImage): string => {
const baseName = image.originalName;
const extension = IMAGE_FORMATS.find((f) => f.format === image.outputFormat)?.extension || 'jpg';
if (image.downloadCount === 0) {
return `${baseName}.${extension}`;
}
return `${baseName}(${image.downloadCount}).${extension}`;
};
const handleDownload = (imageId: string) => {
setConvertedImages((prev) =>
prev.map((img) =>
img.id === imageId ? { ...img, downloadCount: img.downloadCount + 1 } : img
)
);
const image = convertedImages.find((img) => img.id === imageId);
if (image) {
const link = document.createElement('a');
link.href = image.preview;
link.download = getDownloadFilename(image);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
const handleBackToUpload = () => {
setCurrentPage('upload');
setUploadedImages([]);
setConvertedImages([]);
setSelectedFormat('JPEG');
};
if (currentPage === 'download') {
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-8">
<div className="max-w-6xl mx-auto">
<button
onClick={handleBackToUpload}
className="mb-8 px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
>
← Back to Upload
</button>
<h1 className="text-4xl font-bold text-gray-800 mb-2">Converted Images</h1>
<p className="text-gray-600 mb-8">
Your images have been converted to {selectedFormat}. Download them below.
</p>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{convertedImages.map((image) => (
<div
key={image.id}
className="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition"
>
<div className="relative w-full h-48 bg-gray-100">
<img
src={image.preview}
alt={image.originalName}
className="w-full h-full object-cover"
/>
</div>
<div className="p-6">
<h3 className="font-semibold text-gray-800 mb-2 truncate">
{image.originalName}
</h3>
<div className="space-y-2 mb-4 text-sm text-gray-600">
<p>
<span className="font-medium">Original:</span> {image.originalFormat}
</p>
<p>
<span className="font-medium">Output:</span> {image.outputFormat}
</p>
<p>
<span className="font-medium">Size:</span> {formatFileSize(image.size)}
</p>
</div>
<button
onClick={() => handleDownload(image.id)}
className="w-full bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-3 rounded-lg font-semibold hover:from-blue-600 hover:to-indigo-700 transition flex items-center justify-center gap-2"
>
<Download size={20} />
Download Image
</button>
{image.downloadCount > 0 && (
<p className="text-xs text-gray-500 mt-2 text-center">
Downloaded {image.downloadCount} time(s)
</p>
)}
</div>
</div>
))}
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-8">
<div className="max-w-6xl mx-auto">
<div className="mb-12">
<h1 className="text-4xl font-bold text-gray-800 mb-2">Image Format Converter</h1>
<p className="text-gray-600">
Upload images and convert them to your desired format
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Upload Section */}
<div className="lg:col-span-2">
<div className="bg-white rounded-xl shadow-lg p-8 mb-8">
<h2 className="text-2xl font-bold text-gray-800 mb-6">Upload Images</h2>
{/* Drag and Drop Area */}
<div
onDragEnter={handleDrag}
onDragLeave={handleDrag}
onDragOver={handleDrag}
onDrop={handleDrop}
className={`border-2 border-dashed rounded-xl p-12 text-center transition ${
dragActive
? 'border-blue-500 bg-blue-50'
: 'border-gray-300 bg-gray-50 hover:border-gray-400'
}`}
>
<Upload size={48} className="mx-auto mb-4 text-gray-400" />
<p className="text-lg font-semibold text-gray-700 mb-2">
Drag and drop images here
</p>
<p className="text-gray-500 mb-4">or</p>
<label className="inline-block">
<input
type="file"
multiple
accept="image/*"
onChange={handleFileInput}
className="hidden"
/>
<span className="px-6 py-3 bg-blue-500 text-white rounded-lg font-semibold hover:bg-blue-600 transition cursor-pointer inline-block">
Select Files
</span>
</label>
</div>
{/* Uploaded Images List */}
{uploadedImages.length > 0 && (
<div className="mt-8">
<h3 className="text-lg font-semibold text-gray-800 mb-4">
Uploaded Images ({uploadedImages.length})
</h3>
<div className="space-y-3">
{uploadedImages.map((image) => (
<div
key={image.id}
className="flex items-center justify-between bg-gray-50 p-4 rounded-lg border border-gray-200"
>
<div className="flex items-center gap-4 flex-1">
<img
src={image.preview}
alt={image.name}
className="w-12 h-12 object-cover rounded"
/>
<div className="flex-1">
<p className="font-medium text-gray-800 truncate">{image.name}</p>
<p className="text-sm text-gray-500">
{image.originalFormat} • {formatFileSize(image.size)}
</p>
</div>
</div>
<button
onClick={() => removeImage(image.id)}
className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition"
>
<X size={20} />
</button>
</div>
))}
</div>
</div>
)}
</div>
</div>
{/* Format Selection Section */}
<div className="lg:col-span-1">
<div className="bg-white rounded-xl shadow-lg p-8 sticky top-8">
<h2 className="text-2xl font-bold text-gray-800 mb-6">Output Format</h2>
<div className="space-y-3 mb-8 max-h-96 overflow-y-auto">
{IMAGE_FORMATS.map((fmt) => (
<label
key={fmt.format}
className={`flex items-center p-4 rounded-lg border-2 cursor-pointer transition ${
selectedFormat === fmt.format
? 'border-blue-500 bg-blue-50'
: 'border-gray-200 bg-gray-50 hover:border-gray-300'
}`}
>
<input
type="radio"
name="format"
value={fmt.format}
checked={selectedFormat === fmt.format}
onChange={(e) => setSelectedFormat(e.target.value)}
className="w-4 h-4 text-blue-500"
/>
<div className="ml-3 flex-1">
<p className="font-semibold text-gray-800">{fmt.format}</p>
<p className="text-xs text-gray-500">{fmt.estimatedSize}</p>
</div>
</label>
))}
</div>
<button
onClick={handleStartConversion}
disabled={uploadedImages.length === 0}
className={`w-full py-3 rounded-lg font-semibold flex items-center justify-center gap-2 transition ${
uploadedImages.length === 0
? 'bg-gray-300 text-gray-500 cursor-not-allowed'
: 'bg-gradient-to-r from-green-500 to-emerald-600 text-white hover:from-green-600 hover:to-emerald-700'
}`}
>
<span>Start Conversion</span>
<ArrowRight size={20} />
</button>
{uploadedImages.length === 0 && (
<p className="text-xs text-gray-500 text-center mt-3">
Upload images to start conversion
</p>
)}
</div>
</div>
</div>
</div>
</div>
);
}
|