diff --git a/src/components/replace-question-image-button.tsx b/src/components/replace-question-image-button.tsx index a9241f6f..2754818a 100644 --- a/src/components/replace-question-image-button.tsx +++ b/src/components/replace-question-image-button.tsx @@ -1,8 +1,9 @@ "use client"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { ImagePlus, Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; +import { ImageCropper } from "@/components/image-cropper"; import { useLanguage } from "@/contexts/LanguageContext"; import { apiClient } from "@/lib/api-client"; import { frontendLogger } from "@/lib/frontend-logger"; @@ -15,25 +16,39 @@ interface ReplaceQuestionImageButtonProps { onDone: (originalImageUrl: string) => void; } -/** 选择新图片(超过 1MB 时压缩)替换原题图片 */ +/** + * 替换原题图片:与导入题目一样,先选择图片并截取题目所在区域,再保存截取结果(超过 1MB 时压缩) + */ export function ReplaceQuestionImageButton({ errorItemId, hasImage, onDone }: ReplaceQuestionImageButtonProps) { const { t } = useLanguage(); const inputRef = useRef(null); const [uploading, setUploading] = useState(false); + // 待裁剪图片的 object URL,关闭裁剪框或换图时释放 + const [croppingImage, setCroppingImage] = useState(null); + + useEffect(() => () => { + if (croppingImage) URL.revokeObjectURL(croppingImage); + }, [croppingImage]); const handleClick = () => { if (hasImage && !confirm(t.replaceImage.confirm)) return; inputRef.current?.click(); }; - const handleFile = async (file: File | undefined) => { + const handleFile = (file: File | undefined) => { if (!file) return; if (!file.type.startsWith("image/")) { alert(t.replaceImage.invalid); return; } + setCroppingImage(URL.createObjectURL(file)); + }; + + const handleCropComplete = async (croppedBlob: Blob) => { + setCroppingImage(null); setUploading(true); try { + const file = new File([croppedBlob], "question-image.jpg", { type: croppedBlob.type || "image/jpeg" }); const imageDataUrl = await processImageFile(file); const result = await apiClient.put<{ originalImageUrl: string }>(`/api/error-items/${errorItemId}/image`, { imageDataUrl }); onDone(result.originalImageUrl); @@ -55,10 +70,18 @@ export function ReplaceQuestionImageButton({ errorItemId, hasImage, onDone }: Re accept="image/png,image/jpeg,image/webp,image/gif" className="hidden" onChange={(e) => { - void handleFile(e.target.files?.[0]); + handleFile(e.target.files?.[0]); e.target.value = ""; }} /> + {croppingImage && ( + setCroppingImage(null)} + onCropComplete={handleCropComplete} + /> + )}