"use client"; import { useState, useRef, ChangeEvent } from "react"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Upload, Download, Image as ImageIcon } from "lucide-react"; import { toast } from "sonner"; export function ImageConverter() { const [image, setImage] = useState(null); const [previewUrl, setPreviewUrl] = useState(null); const [width, setWidth] = useState(""); const [height, setHeight] = useState(""); const [format, setFormat] = useState<"png" | "jpeg" | "webp">("png"); const [isConverting, setIsConverting] = useState(false); const fileInputRef = useRef(null); const handleImageChange = (e: ChangeEvent) => { const file = e.target.files?.[0]; if (file && file.type.startsWith("image/")) { setImage(file); const reader = new FileReader(); reader.onload = (event) => { const img = new Image(); img.onload = () => { setWidth(img.width); setHeight(img.height); }; img.src = event.target?.result as string; setPreviewUrl(URL.createObjectURL(file)); }; reader.readAsDataURL(file); } else { toast.error("Please select a valid image file."); } }; const handleConvertAndDownload = () => { if (!image || !previewUrl || !width || !height) { toast.error("Please upload an image and set dimensions."); return; } setIsConverting(true); const img = new Image(); img.crossOrigin = "anonymous"; img.src = previewUrl; img.onload = () => { const canvas = document.createElement("canvas"); canvas.width = Number(width); canvas.height = Number(height); const ctx = canvas.getContext("2d"); if (ctx) { ctx.drawImage(img, 0, 0, Number(width), Number(height)); const dataUrl = canvas.toDataURL(`image/${format}`); const link = document.createElement("a"); link.href = dataUrl; const originalName = image.name.substring(0, image.name.lastIndexOf('.')); link.download = `${originalName}_${width}x${height}.${format}`; document.body.appendChild(link); link.click(); document.body.removeChild(link); toast.success("Image exported successfully!"); } else { toast.error("Could not process the image."); } setIsConverting(false); }; img.onerror = () => { toast.error("Failed to load image for conversion."); setIsConverting(false); }; }; return (
{/* Left Column: Settings */} Image Settings Adjust the resolution and format for your export.
setWidth(e.target.value)} disabled={!image} />
setHeight(e.target.value)} disabled={!image} />
{/* Right Column: Preview */}
{previewUrl ? ( Image preview ) : (
fileInputRef.current?.click()} > Click to upload an image
)}
); }