|
| 1 | +import { useState, useRef, useCallback } from 'react'; |
| 2 | +import { ToolShell } from '../../shell/ToolShell'; |
| 3 | +import { useI18n, useToolI18n } from '../../shared/context/I18nContext'; |
| 4 | +import { HelpSection } from '../../shared/components/HelpSection'; |
| 5 | + |
| 6 | +interface ImageInfo { |
| 7 | + name: string; |
| 8 | + width: number; |
| 9 | + height: number; |
| 10 | + originalSize: number; |
| 11 | + compressedSize: number; |
| 12 | + compressedUrl: string; |
| 13 | + compressedBlob: Blob; |
| 14 | + format: string; |
| 15 | +} |
| 16 | + |
| 17 | +function formatBytes(bytes: number): string { |
| 18 | + if (bytes < 1024) return bytes + ' B'; |
| 19 | + if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; |
| 20 | + return (bytes / (1024 * 1024)).toFixed(2) + ' MB'; |
| 21 | +} |
| 22 | + |
| 23 | +export default function ImageCompressor() { |
| 24 | + const { t } = useI18n(); |
| 25 | + const { name, desc, ui, help } = useToolI18n('imgCompress'); |
| 26 | + const [quality, setQuality] = useState(75); |
| 27 | + const [format, setFormat] = useState<'image/jpeg' | 'image/webp' | 'image/png'>('image/jpeg'); |
| 28 | + const [maxWidth, setMaxWidth] = useState(0); |
| 29 | + const [result, setResult] = useState<ImageInfo | null>(null); |
| 30 | + const [processing, setProcessing] = useState(false); |
| 31 | + const [sourceFile, setSourceFile] = useState<File | null>(null); |
| 32 | + const [previewUrl, setPreviewUrl] = useState<string | null>(null); |
| 33 | + const fileInputRef = useRef<HTMLInputElement>(null); |
| 34 | + |
| 35 | + const handleFile = useCallback((file: File) => { |
| 36 | + setSourceFile(file); |
| 37 | + setResult(null); |
| 38 | + if (previewUrl) URL.revokeObjectURL(previewUrl); |
| 39 | + setPreviewUrl(URL.createObjectURL(file)); |
| 40 | + }, [previewUrl]); |
| 41 | + |
| 42 | + const compress = useCallback(() => { |
| 43 | + if (!sourceFile) return; |
| 44 | + setProcessing(true); |
| 45 | + const img = new Image(); |
| 46 | + const url = URL.createObjectURL(sourceFile); |
| 47 | + img.onload = () => { |
| 48 | + URL.revokeObjectURL(url); |
| 49 | + let w = img.width, h = img.height; |
| 50 | + if (maxWidth > 0 && w > maxWidth) { |
| 51 | + h = Math.round(h * (maxWidth / w)); |
| 52 | + w = maxWidth; |
| 53 | + } |
| 54 | + const canvas = document.createElement('canvas'); |
| 55 | + canvas.width = w; |
| 56 | + canvas.height = h; |
| 57 | + const ctx = canvas.getContext('2d')!; |
| 58 | + if (format === 'image/jpeg') { |
| 59 | + ctx.fillStyle = '#ffffff'; |
| 60 | + ctx.fillRect(0, 0, w, h); |
| 61 | + } |
| 62 | + ctx.drawImage(img, 0, 0, w, h); |
| 63 | + canvas.toBlob((blob) => { |
| 64 | + if (!blob) { setProcessing(false); return; } |
| 65 | + setResult({ |
| 66 | + name: sourceFile.name, |
| 67 | + width: w, height: h, |
| 68 | + originalSize: sourceFile.size, |
| 69 | + compressedSize: blob.size, |
| 70 | + compressedUrl: URL.createObjectURL(blob), |
| 71 | + compressedBlob: blob, |
| 72 | + format: format.split('/')[1].toUpperCase(), |
| 73 | + }); |
| 74 | + setProcessing(false); |
| 75 | + }, format, format === 'image/png' ? undefined : quality / 100); |
| 76 | + }; |
| 77 | + img.src = url; |
| 78 | + }, [sourceFile, quality, format, maxWidth]); |
| 79 | + |
| 80 | + const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => { |
| 81 | + const file = e.target.files?.[0]; |
| 82 | + if (file) handleFile(file); |
| 83 | + }, [handleFile]); |
| 84 | + |
| 85 | + const handleDrop = useCallback((e: React.DragEvent) => { |
| 86 | + e.preventDefault(); |
| 87 | + const file = e.dataTransfer.files[0]; |
| 88 | + if (file && file.type.startsWith('image/')) handleFile(file); |
| 89 | + }, [handleFile]); |
| 90 | + |
| 91 | + const download = () => { |
| 92 | + if (!result) return; |
| 93 | + const ext = format.split('/')[1]; |
| 94 | + const baseName = result.name.replace(/\.[^.]+$/, ''); |
| 95 | + const link = document.createElement('a'); |
| 96 | + link.download = `${baseName}-compressed.${ext}`; |
| 97 | + link.href = result.compressedUrl; |
| 98 | + link.click(); |
| 99 | + }; |
| 100 | + |
| 101 | + const ratio = result ? Math.round((1 - result.compressedSize / result.originalSize) * 100) : 0; |
| 102 | + |
| 103 | + return ( |
| 104 | + <ToolShell title={name} description={desc}> |
| 105 | + <div className="tool-layout"> |
| 106 | + <div className="tool-panel"> |
| 107 | + <div className="panel-header">{t('common.settings')}</div> |
| 108 | + <div className="uuid-config"> |
| 109 | + <div className="uuid-config-row"> |
| 110 | + <label>{ui.format}</label> |
| 111 | + <div className="panel-actions"> |
| 112 | + {(['image/jpeg', 'image/webp', 'image/png'] as const).map((f) => ( |
| 113 | + <button key={f} className={`panel-btn panel-btn-sm${format === f ? ' accent' : ''}`} onClick={() => setFormat(f)}>{f.split('/')[1].toUpperCase()}</button> |
| 114 | + ))} |
| 115 | + </div> |
| 116 | + </div> |
| 117 | + {format !== 'image/png' && ( |
| 118 | + <div className="uuid-config-row"> |
| 119 | + <label>{ui.quality}</label> |
| 120 | + <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1 }}> |
| 121 | + <input type="range" min={10} max={100} value={quality} onChange={(e) => setQuality(parseInt(e.target.value))} style={{ flex: 1 }} /> |
| 122 | + <span style={{ fontSize: 14, fontFamily: 'var(--font-mono)', minWidth: 36, textAlign: 'right' }}>{quality}%</span> |
| 123 | + </div> |
| 124 | + </div> |
| 125 | + )} |
| 126 | + {format === 'image/png' && ( |
| 127 | + <div style={{ fontSize: 12, color: 'var(--amber)', padding: '4px 0' }}>{ui.pngTip}</div> |
| 128 | + )} |
| 129 | + <div className="uuid-config-row"> |
| 130 | + <label>{ui.maxWidth}</label> |
| 131 | + <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1 }}> |
| 132 | + <input type="range" min={0} max={3840} step={100} value={maxWidth} onChange={(e) => setMaxWidth(parseInt(e.target.value))} style={{ flex: 1 }} /> |
| 133 | + <span style={{ fontSize: 14, fontFamily: 'var(--font-mono)', minWidth: 48, textAlign: 'right' }}>{maxWidth === 0 ? ui.noLimit : maxWidth + 'px'}</span> |
| 134 | + </div> |
| 135 | + </div> |
| 136 | + </div> |
| 137 | + <input ref={fileInputRef} type="file" accept="image/*" onChange={handleFileInput} style={{ display: 'none' }} /> |
| 138 | + <div className="qr-dropzone" onDragOver={(e) => e.preventDefault()} onDrop={handleDrop} onClick={() => fileInputRef.current?.click()} style={{ margin: '12px 16px', padding: '24px 16px', cursor: 'pointer' }}> |
| 139 | + <div style={{ color: 'var(--muted)', fontSize: 13, textAlign: 'center' }}> |
| 140 | + {sourceFile ? `${sourceFile.name} (${formatBytes(sourceFile.size)})` : ui.dropzone} |
| 141 | + </div> |
| 142 | + </div> |
| 143 | + {sourceFile && ( |
| 144 | + <button className="panel-btn accent" onClick={compress} disabled={processing} style={{ margin: '0 16px 12px', width: 'calc(100% - 32px)' }}> |
| 145 | + {processing ? ui.processing : ui.compress} |
| 146 | + </button> |
| 147 | + )} |
| 148 | + </div> |
| 149 | + <div className="tool-panel"> |
| 150 | + <div className="panel-header">{t('common.output')}</div> |
| 151 | + {result ? ( |
| 152 | + <div style={{ padding: 16 }}> |
| 153 | + <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16, background: 'var(--surface-2)', borderRadius: 8, padding: 8 }}> |
| 154 | + <img src={result.compressedUrl} alt="" style={{ maxWidth: '100%', maxHeight: 300, borderRadius: 4 }} /> |
| 155 | + </div> |
| 156 | + <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 13 }}> |
| 157 | + <div><span style={{ color: 'var(--muted)' }}>{ui.originalSize}: </span>{formatBytes(result.originalSize)}</div> |
| 158 | + <div><span style={{ color: 'var(--muted)' }}>{ui.compressedSize}: </span>{formatBytes(result.compressedSize)}</div> |
| 159 | + <div><span style={{ color: 'var(--muted)' }}>{ui.dimensions}: </span>{result.width}×{result.height}</div> |
| 160 | + <div><span style={{ color: 'var(--muted)' }}>{ui.reduction}: </span><span style={{ color: ratio > 0 ? 'var(--green)' : 'var(--red)', fontWeight: 600 }}>{ratio > 0 ? '-' : '+'}{Math.abs(ratio)}%</span></div> |
| 161 | + </div> |
| 162 | + {ratio < 0 && <div style={{ fontSize: 12, color: 'var(--amber)', marginTop: 8 }}>{ui.sizeIncreased}</div>} |
| 163 | + <button className="panel-btn accent" onClick={download} style={{ marginTop: 16, width: '100%' }}>{t('common.download')}</button> |
| 164 | + </div> |
| 165 | + ) : previewUrl ? ( |
| 166 | + <div style={{ padding: 16 }}> |
| 167 | + <div style={{ display: 'flex', justifyContent: 'center', background: 'var(--surface-2)', borderRadius: 8, padding: 8 }}> |
| 168 | + <img src={previewUrl} alt="" style={{ maxWidth: '100%', maxHeight: 300, borderRadius: 4 }} /> |
| 169 | + </div> |
| 170 | + <div style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 12, marginTop: 8 }}>{ui.adjustHint}</div> |
| 171 | + </div> |
| 172 | + ) : ( |
| 173 | + <div style={{ padding: 48, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>{t('common.waiting')}</div> |
| 174 | + )} |
| 175 | + </div> |
| 176 | + </div> |
| 177 | + {help && <HelpSection title={help.title} features={help.features} usage={help.usage} params={help.params} />} |
| 178 | + </ToolShell> |
| 179 | + ); |
| 180 | +} |
0 commit comments