Converto_Web_ReactApp / src /pageindex.tsx
pakdeveloper's picture
Upload 16 files
ad8820e verified
Raw History Blame Contribute Delete
13.5 kB
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>
);
}