inpainting-canvas.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. 'use client';
  2. import { useRef, useEffect, useState, useCallback } from 'react';
  3. import { Button } from '@/components/ui/button';
  4. import { Card, CardContent } from '@/components/ui/card';
  5. import { Label } from '@/components/ui/label';
  6. import { Upload, Download, Eraser, Brush, RotateCcw } from 'lucide-react';
  7. import { fileToBase64 } from '@/lib/utils';
  8. interface InpaintingCanvasProps {
  9. onSourceImageChange: (image: string) => void;
  10. onMaskImageChange: (image: string) => void;
  11. className?: string;
  12. }
  13. export function InpaintingCanvas({
  14. onSourceImageChange,
  15. onMaskImageChange,
  16. className
  17. }: InpaintingCanvasProps) {
  18. const canvasRef = useRef<HTMLCanvasElement>(null);
  19. const maskCanvasRef = useRef<HTMLCanvasElement>(null);
  20. const fileInputRef = useRef<HTMLInputElement>(null);
  21. const [sourceImage, setSourceImage] = useState<string | null>(null);
  22. const [isDrawing, setIsDrawing] = useState(false);
  23. const [brushSize, setBrushSize] = useState(20);
  24. const [isEraser, setIsEraser] = useState(false);
  25. const [canvasSize, setCanvasSize] = useState({ width: 512, height: 512 });
  26. // Initialize canvases
  27. useEffect(() => {
  28. const canvas = canvasRef.current;
  29. const maskCanvas = maskCanvasRef.current;
  30. if (!canvas || !maskCanvas) return;
  31. const ctx = canvas.getContext('2d');
  32. const maskCtx = maskCanvas.getContext('2d');
  33. if (!ctx || !maskCtx) return;
  34. // Set canvas size
  35. canvas.width = canvasSize.width;
  36. canvas.height = canvasSize.height;
  37. maskCanvas.width = canvasSize.width;
  38. maskCanvas.height = canvasSize.height;
  39. // Initialize mask canvas with black (no inpainting)
  40. maskCtx.fillStyle = 'black';
  41. maskCtx.fillRect(0, 0, canvasSize.width, canvasSize.height);
  42. // Update mask image
  43. updateMaskImage();
  44. }, [canvasSize]);
  45. const updateMaskImage = useCallback(() => {
  46. const maskCanvas = maskCanvasRef.current;
  47. if (!maskCanvas) return;
  48. const maskDataUrl = maskCanvas.toDataURL();
  49. onMaskImageChange(maskDataUrl);
  50. }, [onMaskImageChange]);
  51. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  52. const file = e.target.files?.[0];
  53. if (!file) return;
  54. try {
  55. const base64 = await fileToBase64(file);
  56. setSourceImage(base64);
  57. onSourceImageChange(base64);
  58. // Load image to get dimensions and update canvas size
  59. const img = new Image();
  60. img.onload = () => {
  61. // Calculate scaled dimensions to fit within 512x512 while maintaining aspect ratio
  62. const maxSize = 512;
  63. let width = img.width;
  64. let height = img.height;
  65. if (width > maxSize || height > maxSize) {
  66. const aspectRatio = width / height;
  67. if (width > height) {
  68. width = maxSize;
  69. height = maxSize / aspectRatio;
  70. } else {
  71. height = maxSize;
  72. width = maxSize * aspectRatio;
  73. }
  74. }
  75. setCanvasSize({ width: Math.round(width), height: Math.round(height) });
  76. // Draw image on canvas
  77. const canvas = canvasRef.current;
  78. if (!canvas) return;
  79. const ctx = canvas.getContext('2d');
  80. if (!ctx) return;
  81. canvas.width = width;
  82. canvas.height = height;
  83. ctx.drawImage(img, 0, 0, width, height);
  84. // Update mask canvas size
  85. const maskCanvas = maskCanvasRef.current;
  86. if (!maskCanvas) return;
  87. const maskCtx = maskCanvas.getContext('2d');
  88. if (!maskCtx) return;
  89. maskCanvas.width = width;
  90. maskCanvas.height = height;
  91. maskCtx.fillStyle = 'black';
  92. maskCtx.fillRect(0, 0, width, height);
  93. updateMaskImage();
  94. };
  95. img.src = base64;
  96. } catch (err) {
  97. console.error('Failed to load image:', err);
  98. }
  99. };
  100. const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
  101. if (!sourceImage) return;
  102. setIsDrawing(true);
  103. draw(e);
  104. };
  105. const stopDrawing = () => {
  106. setIsDrawing(false);
  107. };
  108. const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
  109. if (!isDrawing || !sourceImage) return;
  110. const canvas = maskCanvasRef.current;
  111. if (!canvas) return;
  112. const ctx = canvas.getContext('2d');
  113. if (!ctx) return;
  114. const rect = canvas.getBoundingClientRect();
  115. const scaleX = canvas.width / rect.width;
  116. const scaleY = canvas.height / rect.height;
  117. const x = (e.clientX - rect.left) * scaleX;
  118. const y = (e.clientY - rect.top) * scaleY;
  119. ctx.globalCompositeOperation = isEraser ? 'destination-out' : 'source-over';
  120. ctx.fillStyle = isEraser ? 'black' : 'white';
  121. ctx.beginPath();
  122. ctx.arc(x, y, brushSize, 0, Math.PI * 2);
  123. ctx.fill();
  124. updateMaskImage();
  125. };
  126. const clearMask = () => {
  127. const canvas = maskCanvasRef.current;
  128. if (!canvas) return;
  129. const ctx = canvas.getContext('2d');
  130. if (!ctx) return;
  131. ctx.fillStyle = 'black';
  132. ctx.fillRect(0, 0, canvas.width, canvas.height);
  133. updateMaskImage();
  134. };
  135. const downloadMask = () => {
  136. const canvas = maskCanvasRef.current;
  137. if (!canvas) return;
  138. const link = document.createElement('a');
  139. link.download = 'inpainting-mask.png';
  140. link.href = canvas.toDataURL();
  141. link.click();
  142. };
  143. return (
  144. <div className={`space-y-4 ${className}`}>
  145. <Card>
  146. <CardContent className="pt-6">
  147. <div className="space-y-4">
  148. <div className="space-y-2">
  149. <Label>Source Image</Label>
  150. <div className="space-y-4">
  151. {sourceImage && (
  152. <div className="relative">
  153. <img
  154. src={sourceImage}
  155. alt="Source"
  156. className="w-full rounded-lg border border-border"
  157. style={{ maxWidth: '512px', height: 'auto' }}
  158. />
  159. </div>
  160. )}
  161. <Button
  162. type="button"
  163. variant="outline"
  164. onClick={() => fileInputRef.current?.click()}
  165. className="w-full"
  166. >
  167. <Upload className="h-4 w-4 mr-2" />
  168. {sourceImage ? 'Change Image' : 'Upload Image'}
  169. </Button>
  170. <input
  171. ref={fileInputRef}
  172. type="file"
  173. accept="image/*"
  174. onChange={handleImageUpload}
  175. className="hidden"
  176. />
  177. </div>
  178. </div>
  179. {sourceImage && (
  180. <>
  181. <div className="space-y-2">
  182. <Label>Mask Editor</Label>
  183. <div className="relative">
  184. <canvas
  185. ref={canvasRef}
  186. className="absolute inset-0 rounded-lg border border-border"
  187. style={{ maxWidth: '512px', height: 'auto' }}
  188. />
  189. <canvas
  190. ref={maskCanvasRef}
  191. className="relative rounded-lg border border-border cursor-crosshair"
  192. style={{ maxWidth: '512px', height: 'auto', opacity: 0.7 }}
  193. onMouseDown={startDrawing}
  194. onMouseUp={stopDrawing}
  195. onMouseMove={draw}
  196. onMouseLeave={stopDrawing}
  197. />
  198. </div>
  199. <p className="text-xs text-muted-foreground">
  200. White areas will be inpainted, black areas will be preserved
  201. </p>
  202. </div>
  203. <div className="space-y-2">
  204. <Label htmlFor="brush_size">
  205. Brush Size: {brushSize}px
  206. </Label>
  207. <input
  208. id="brush_size"
  209. type="range"
  210. value={brushSize}
  211. onChange={(e) => setBrushSize(Number(e.target.value))}
  212. min={1}
  213. max={100}
  214. className="w-full"
  215. />
  216. </div>
  217. <div className="flex gap-2">
  218. <Button
  219. type="button"
  220. variant={isEraser ? "default" : "outline"}
  221. onClick={() => setIsEraser(true)}
  222. className="flex-1"
  223. >
  224. <Eraser className="h-4 w-4 mr-2" />
  225. Eraser
  226. </Button>
  227. <Button
  228. type="button"
  229. variant={!isEraser ? "default" : "outline"}
  230. onClick={() => setIsEraser(false)}
  231. className="flex-1"
  232. >
  233. <Brush className="h-4 w-4 mr-2" />
  234. Brush
  235. </Button>
  236. </div>
  237. <div className="flex gap-2">
  238. <Button
  239. type="button"
  240. variant="outline"
  241. onClick={clearMask}
  242. className="flex-1"
  243. >
  244. <RotateCcw className="h-4 w-4 mr-2" />
  245. Clear Mask
  246. </Button>
  247. <Button
  248. type="button"
  249. variant="outline"
  250. onClick={downloadMask}
  251. className="flex-1"
  252. >
  253. <Download className="h-4 w-4 mr-2" />
  254. Download Mask
  255. </Button>
  256. </div>
  257. </>
  258. )}
  259. </div>
  260. </CardContent>
  261. </Card>
  262. </div>
  263. );
  264. }