Processing...
{state.status}
No Image Loaded
Upload an image to get started
import React, { useReducer, useState, useEffect, useRef, useCallback } from 'react'; import { Upload, Download, Layers, Image as ImageIcon, Wand2, Sliders, AlertCircle, CheckCircle, Trash2, ZoomIn, ZoomOut } from 'lucide-react'; import ImageTracer from 'imagetracerjs'; // --- State Management --- const initialState = { status: 'IDLE', imageSrc: null, processedSvg: null, settings: { tolerance: 30, simplification: 0.5, colorCount: 2, bgColor: '#ffffff', scale: 1, ltres: 1, qtres: 1, pathomit: 8, rightangleenhance: true }, error: null, zoom: 100 }; const reducer = (state, action) => { switch (action.type) { case 'SET_STATUS': return { ...state, status: action.payload }; case 'SET_IMAGE': return { ...state, imageSrc: action.payload, status: 'MASKING' }; case 'SET_SETTINGS': return { ...state, settings: { ...state.settings, ...action.payload } }; case 'SET_SVG': return { ...state, processedSvg: action.payload, status: 'READY' }; case 'SET_ERROR': return { ...state, error: action.payload, status: 'IDLE' }; case 'RESET': return initialState; case 'SET_ZOOM': return { ...state, zoom: action.payload }; case 'CLEAR_SVG': return { ...state, processedSvg: null, status: 'MASKING' }; default: return state; } }; // --- Engine: HEIC to JPEG/Blob Conversion --- const convertHeicToBlob = async (file) => { try { const heic2any = (await import('heic2any')).default; const converted = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.9 }); return converted; } catch (error) { console.error('HEIC conversion failed:', error); return file; } }; // --- Engine: Advanced Background Removal --- const removeBackgroundAdvanced = (canvas, tolerance, bgColor) => { const ctx = canvas.getContext('2d'); const width = canvas.width; const height = canvas.height; const imageData = ctx.getImageData(0, 0, width, height); const data = imageData.data; // Parse background color const bgRgb = hexToRgb(bgColor); for (let i = 0; i < data.length; i += 4) { const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; // Calculate color distance const distance = Math.sqrt( Math.pow(r - bgRgb.r, 2) + Math.pow(g - bgRgb.g, 2) + Math.pow(b - bgRgb.b, 2) ); // Also check if pixel is close to white/light (common background) const brightness = (r + g + b) / 3; const isLightBackground = brightness > 240 && distance < 50; if (distance < tolerance || isLightBackground) { data[i + 3] = 0; // Set alpha to 0 (transparent) } } ctx.putImageData(imageData, 0, 0); }; // Helper: Hex to RGB const hexToRgb = (hex) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : { r: 255, g: 255, b: 255 }; }; // --- Engine: Real SVG Vectorization --- const vectorizeImage = (canvas, settings) => { return new Promise((resolve, reject) => { try { const tracerOptions = { ltres: settings.ltres, qtres: settings.qtres, pathomit: settings.pathomit, colorsampling: 2, numberofcolors: settings.colorCount, mincolorratio: 0, colorquantcycles: 3, scale: settings.scale, simplify: settings.simplification, rightangleenhance: settings.rightangleenhance, blurradius: 0, blurdelta: 20 }; ImageTracer.imageToSVG( canvas.toDataURL('image/png'), (svgString) => { resolve(svgString); }, tracerOptions ); } catch (error) { reject(error); } }); }; // --- Engine: SVG Sanitizer for Cutting Machines --- const sanitizeSvgForCutting = (svgString) => { const parser = new DOMParser(); const doc = parser.parseFromString(svgString, 'image/svg+xml'); const svgElement = doc.querySelector('svg'); if (!svgElement) return svgString; // Remove unwanted elements ['metadata', 'desc', 'style', 'image', 'clipPath', 'mask'].forEach(tag => { const elements = svgElement.querySelectorAll(tag); elements.forEach(el => el.remove()); }); // Set proper viewBox and dimensions svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); // Convert all styles to attributes const elements = svgElement.querySelectorAll('*'); elements.forEach(el => { const style = el.getAttribute('style'); if (style) { const styleObj = {}; style.split(';').forEach(rule => { const [prop, val] = rule.split(':'); if (prop && val) styleObj[prop.trim()] = val.trim(); }); if (styleObj['fill']) el.setAttribute('fill', styleObj['fill']); if (styleObj['stroke']) el.setAttribute('stroke', styleObj['stroke']); if (styleObj['stroke-width']) el.setAttribute('stroke-width', styleObj['stroke-width']); if (styleObj['opacity']) el.setAttribute('opacity', styleObj['opacity']); el.removeAttribute('style'); } // Ensure paths have proper fill for cutting if (el.tagName === 'path' && !el.getAttribute('fill')) { el.setAttribute('fill', '#000000'); } }); return `\n${svgElement.outerHTML}`; }; // --- Main Application Component --- export default function CutForgeStudio() { const [state, dispatch] = useReducer(reducer, initialState); const canvasRef = useRef(null); const imageRef = useRef(null); const containerRef = useRef(null); const [previewMode, setPreviewMode] = useState('original'); // 'original', 'masked', 'vector' // --- Handlers --- const handleFileUpload = async (e) => { const file = e.target.files[0]; if (!file) return; dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' }); dispatch({ type: 'SET_ERROR', payload: null }); try { let processedFile = file; // Handle HEIC files if (file.name.toLowerCase().endsWith('.heic')) { dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' }); processedFile = await convertHeicToBlob(file); } const url = URL.createObjectURL(processedFile); imageRef.current.src = url; imageRef.current.onload = () => { dispatch({ type: 'SET_IMAGE', payload: url }); processImage(url); }; } catch (err) { console.error('Upload error:', err); dispatch({ type: 'SET_ERROR', payload: 'Failed to load image. Please try again.' }); dispatch({ type: 'SET_STATUS', payload: 'IDLE' }); } }; const processImage = useCallback((src) => { const canvas = canvasRef.current; const img = imageRef.current; if (!canvas || !img) return; // Set canvas dimensions (max 2000px for performance) const maxSize = 2000; let width = img.naturalWidth; let height = img.naturalHeight; if (width > maxSize || height > maxSize) { const ratio = Math.min(maxSize / width, maxSize / height); width = Math.floor(width * ratio); height = Math.floor(height * ratio); } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // Apply background removal removeBackgroundAdvanced(canvas, state.settings.tolerance, state.settings.bgColor); dispatch({ type: 'SET_STATUS', payload: 'MASKING' }); setPreviewMode('masked'); }, [state.settings.tolerance, state.settings.bgColor]); const generateVector = useCallback(async () => { if (!canvasRef.current) return; dispatch({ type: 'SET_STATUS', payload: 'VECTORIZING' }); try { const rawSvg = await vectorizeImage(canvasRef.current, state.settings); const cleanSvg = sanitizeSvgForCutting(rawSvg); dispatch({ type: 'SET_SVG', payload: cleanSvg }); setPreviewMode('vector'); } catch (error) { console.error('Vectorization error:', error); dispatch({ type: 'SET_ERROR', payload: 'Vectorization failed. Try adjusting settings.' }); dispatch({ type: 'SET_STATUS', payload: 'MASKING' }); } }, [state.settings]); const downloadSvg = () => { if (!state.processedSvg) return; const blob = new Blob([state.processedSvg], { type: 'image/svg+xml;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `cutforge-${Date.now()}.svg`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; const downloadPreview = () => { if (!canvasRef.current) return; const link = document.createElement('a'); link.download = `cutforge-preview-${Date.now()}.png`; link.href = canvasRef.current.toDataURL('image/png'); link.click(); }; const handleZoom = (delta) => { const newZoom = Math.max(25, Math.min(400, state.zoom + delta)); dispatch({ type: 'SET_ZOOM', payload: newZoom }); }; const resetWorkspace = () => { dispatch({ type: 'RESET' }); setPreviewMode('original'); if (canvasRef.current) { const ctx = canvasRef.current.getContext('2d'); ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); } }; // Re-process when settings change useEffect(() => { if (state.imageSrc && state.status === 'MASKING' || state.status === 'READY') { const timer = setTimeout(() => { processImage(state.imageSrc); }, 300); return () => clearTimeout(timer); } }, [state.settings.tolerance, state.settings.bgColor, state.imageSrc]); // --- Render Helpers --- const renderStatusBadge = () => { const config = { IDLE: { color: 'bg-gray-200 text-gray-600', label: 'Ready' }, UPLOADING: { color: 'bg-saffron text-ink', label: 'Uploading...' }, MASKING: { color: 'bg-forest text-white', label: 'Processing' }, VECTORIZING: { color: 'bg-forest text-white animate-pulse', label: 'Vectorizing...' }, READY: { color: 'bg-saffron text-ink', label: 'Complete' } }; const { color, label } = config[state.status]; return ( {label} ); }; return (
Processing...
{state.status}
No Image Loaded
Upload an image to get started