fix(scanner): recorte automatico de la fotografia segun el marco guia del DNI

This commit is contained in:
Carlos Tello
2026-10-14 19:14:41 -03:00
parent 0e2ea24f05
commit 8debd4c7fc
@@ -30,6 +30,8 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
onScanSuccess, onScanSuccess,
}) => { }) => {
const videoRef = useRef<HTMLVideoElement | null>(null); const videoRef = useRef<HTMLVideoElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const guideRef = useRef<HTMLDivElement | null>(null);
const streamRef = useRef<MediaStream | null>(null); const streamRef = useRef<MediaStream | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null); const fileInputRef = useRef<HTMLInputElement | null>(null);
const zxingReaderRef = useRef<MultiFormatReader | null>(null); const zxingReaderRef = useRef<MultiFormatReader | null>(null);
@@ -277,7 +279,10 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
}; };
// Motor Multi-Paso para extraer PDF417 o QR DNI 2026 de la foto capturada // Motor Multi-Paso para extraer PDF417 o QR DNI 2026 de la foto capturada
const processImageExtraction = async (sourceCanvas: HTMLCanvasElement) => { const processImageExtraction = async (
sourceCanvas: HTMLCanvasElement,
fallbackCanvas?: HTMLCanvasElement
) => {
setStep('ANALYZING'); setStep('ANALYZING');
setErrorMsg(null); setErrorMsg(null);
@@ -363,6 +368,12 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
} }
} }
// Paso 6: Si no se detectó en el recorte, intentar en el fotograma completo
if (!rawText && fallbackCanvas) {
setAnalyzingStatus('Buscando en fotograma completo alternativo...');
rawText = await tryDecodeCanvas(fallbackCanvas);
}
// Resultado final de extracción // Resultado final de extracción
if (rawText) { if (rawText) {
try { try {
@@ -389,7 +400,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
} }
}; };
// Acción Principal: Tomar Foto desde la Cámara en Vivo // Acción Principal: Tomar Foto desde la Cámara en Vivo y Recortarla al Marco
const handleCapturePhoto = async () => { const handleCapturePhoto = async () => {
if (!videoRef.current) return; if (!videoRef.current) return;
const video = videoRef.current; const video = videoRef.current;
@@ -434,14 +445,72 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
return; return;
} }
const photoUrl = canvas.toDataURL('image/jpeg', 0.95); // 3. RECORTE AUTOMÁTICO EXACTO DE LA FOTO AL MARCO/GUÍA DEL DNI
let cropX = 0;
let cropY = 0;
let cropW = canvas.width;
let cropH = canvas.height;
if (containerRef.current && guideRef.current && videoRef.current) {
const cRect = containerRef.current.getBoundingClientRect();
const gRect = guideRef.current.getBoundingClientRect();
const vw = canvas.width;
const vh = canvas.height;
const cw = cRect.width;
const ch = cRect.height;
if (cw > 0 && ch > 0) {
// En video con objectFit: 'cover'
const scale = Math.max(cw / vw, ch / vh);
const renderedW = vw * scale;
const renderedH = vh * scale;
const offsetX = (cw - renderedW) / 2;
const offsetY = (ch - renderedH) / 2;
const gLeft = gRect.left - cRect.left;
const gTop = gRect.top - cRect.top;
// Mapear de coordenadas visuales de pantalla a píxeles reales de la imagen
cropX = Math.round((gLeft - offsetX) / scale);
cropY = Math.round((gTop - offsetY) / scale);
cropW = Math.round(gRect.width / scale);
cropH = Math.round(gRect.height / scale);
// Clamping seguro dentro de los límites de la imagen
cropX = Math.max(0, Math.min(cropX, vw - 20));
cropY = Math.max(0, Math.min(cropY, vh - 20));
cropW = Math.max(20, Math.min(cropW, vw - cropX));
cropH = Math.max(20, Math.min(cropH, vh - cropY));
}
} else {
// Fallback a recorte central estándar de tarjeta DNI (relación 1.58 : 1)
const targetW = Math.round(canvas.width * 0.85);
const targetH = Math.round(targetW / 1.58);
cropX = Math.max(0, Math.round((canvas.width - targetW) / 2));
cropY = Math.max(0, Math.round((canvas.height - targetH) / 2));
cropW = Math.min(targetW, canvas.width - cropX);
cropH = Math.min(targetH, canvas.height - cropY);
}
// Crear canvas con la imagen recortada del DNI
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = cropW;
croppedCanvas.height = cropH;
const croppedCtx = croppedCanvas.getContext('2d');
if (croppedCtx) {
croppedCtx.drawImage(canvas, cropX, cropY, cropW, cropH, 0, 0, cropW, cropH);
}
// Foto final recortada para visualización y análisis
const finalDisplayCanvas = croppedCtx ? croppedCanvas : canvas;
const photoUrl = finalDisplayCanvas.toDataURL('image/jpeg', 0.95);
setCapturedPhotoUrl(photoUrl); setCapturedPhotoUrl(photoUrl);
// Detener la cámara temporalmente para congelar la imagen capturada // Detener la cámara temporalmente para congelar la imagen capturada
stopCamera(); stopCamera();
// Iniciar escaneo multi-paso sobre la foto // Iniciar escaneo multi-paso sobre la foto recortada (con fallback al fotograma completo si hiciera falta)
await processImageExtraction(canvas); await processImageExtraction(finalDisplayCanvas, canvas);
}; };
// Manejador para fotos cargadas desde archivo o app de cámara nativa // Manejador para fotos cargadas desde archivo o app de cámara nativa
@@ -454,7 +523,6 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
const dataUrl = event.target?.result as string; const dataUrl = event.target?.result as string;
if (!dataUrl) return; if (!dataUrl) return;
setCapturedPhotoUrl(dataUrl);
stopCamera(); stopCamera();
const img = new Image(); const img = new Image();
@@ -465,7 +533,26 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (ctx) { if (ctx) {
ctx.drawImage(img, 0, 0); ctx.drawImage(img, 0, 0);
await processImageExtraction(canvas);
// Si la foto es vertical o panorámica, recortar región central del DNI
let finalCanvas = canvas;
const targetW = Math.round(img.width * 0.9);
const targetH = Math.round(targetW / 1.58);
if (targetH < img.height) {
const cropCanvas = document.createElement('canvas');
cropCanvas.width = targetW;
cropCanvas.height = targetH;
const cctx = cropCanvas.getContext('2d');
if (cctx) {
const cx = Math.round((img.width - targetW) / 2);
const cy = Math.round((img.height - targetH) / 2);
cctx.drawImage(img, cx, cy, targetW, targetH, 0, 0, targetW, targetH);
finalCanvas = cropCanvas;
}
}
setCapturedPhotoUrl(finalCanvas.toDataURL('image/jpeg', 0.95));
await processImageExtraction(finalCanvas, canvas);
} }
}; };
img.src = dataUrl; img.src = dataUrl;
@@ -603,6 +690,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
{/* Visor de Cámara / Foto Capturada */} {/* Visor de Cámara / Foto Capturada */}
<div <div
ref={containerRef}
style={{ style={{
position: 'relative', position: 'relative',
width: '100%', width: '100%',
@@ -634,6 +722,7 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
{/* Guía Visual Integral del DNI (Proporción de Tarjeta DNI ~1.58:1) */} {/* Guía Visual Integral del DNI (Proporción de Tarjeta DNI ~1.58:1) */}
<div <div
ref={guideRef}
style={{ style={{
position: 'absolute', position: 'absolute',
width: '85%', width: '85%',
@@ -681,9 +770,26 @@ export const CameraScannerModal: React.FC<CameraScannerModalProps> = ({
{/* VISTA 2: Foto Congelada / Procesamiento / Resultados */} {/* VISTA 2: Foto Congelada / Procesamiento / Resultados */}
{step !== 'PREVIEW' && capturedPhotoUrl && ( {step !== 'PREVIEW' && capturedPhotoUrl && (
<div style={{ position: 'relative', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <div style={{ position: 'relative', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<span
style={{
position: 'absolute',
top: '0.65rem',
left: '0.65rem',
backgroundColor: 'rgba(30, 136, 229, 0.9)',
color: '#fff',
padding: '0.2rem 0.6rem',
borderRadius: '4px',
fontSize: '0.75rem',
fontWeight: 700,
zIndex: 10,
boxShadow: '0 2px 6px rgba(0,0,0,0.4)',
}}
>
✂️ Foto Recortada al DNI
</span>
<img <img
src={capturedPhotoUrl} src={capturedPhotoUrl}
alt="Foto del DNI" alt="Foto del DNI recortada"
style={{ style={{
width: '100%', width: '100%',
height: '100%', height: '100%',