import { buildPaletteLUT, HeatmapPaletteDefinition, } from './heatmapPalettes'; export type DiffVisualMode = 'enhanced' | 'difference' | 'heatmap'; export interface AlignedDiffPair { width: number; height: number; origData: Uint8ClampedArray; resData: Uint8ClampedArray; meanDiffPercent: number; maxDiffPercent: number; } export interface DiffRenderOptions { mode: DiffVisualMode; gain: number; // 1 .. 16 threshold: number; // 0 .. 40 palette: HeatmapPaletteDefinition; backgroundDim: number; // 0 .. 0.9 } const loadImageElement = (src: string): Promise => new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => reject(new Error('Не удалось декодировать изображение')); img.src = src; }); export async function loadAlignedDiffPair( originalUrl: string, resizedUrl: string, maxCalcSide = 1280 ): Promise { const [origImg, resImg] = await Promise.all([ loadImageElement(originalUrl), loadImageElement(resizedUrl), ]); const natW = Math.max(1, origImg.naturalWidth || origImg.width); const natH = Math.max(1, origImg.naturalHeight || origImg.height); const longest = Math.max(natW, natH); const scale = longest > maxCalcSide ? maxCalcSide / longest : 1; const width = Math.max(1, Math.round(natW * scale)); const height = Math.max(1, Math.round(natH * scale)); const canvasA = document.createElement('canvas'); canvasA.width = width; canvasA.height = height; const ctxA = canvasA.getContext('2d', { willReadFrequently: true }); const canvasB = document.createElement('canvas'); canvasB.width = width; canvasB.height = height; const ctxB = canvasB.getContext('2d', { willReadFrequently: true }); if (!ctxA || !ctxB) { throw new Error('Canvas 2D недоступен для анализа отличий'); } ctxA.imageSmoothingEnabled = true; ctxA.imageSmoothingQuality = 'high'; ctxA.drawImage(origImg, 0, 0, width, height); const origData = ctxA.getImageData(0, 0, width, height).data; ctxB.imageSmoothingEnabled = true; ctxB.imageSmoothingQuality = 'high'; ctxB.drawImage(resImg, 0, 0, width, height); const resData = ctxB.getImageData(0, 0, width, height).data; const pixelCount = width * height; let totalDiff = 0; let maxDiff = 0; for (let i = 0; i < origData.length; i += 4) { const dr = Math.abs(origData[i] - resData[i]); const dg = Math.abs(origData[i + 1] - resData[i + 1]); const db = Math.abs(origData[i + 2] - resData[i + 2]); const avg = (dr + dg + db) / 3; totalDiff += avg; if (avg > maxDiff) maxDiff = avg; } return { width, height, origData, resData, meanDiffPercent: (totalDiff / Math.max(1, pixelCount) / 255) * 100, maxDiffPercent: (maxDiff / 255) * 100, }; } export async function renderDiffImageBlob( pair: AlignedDiffPair, options: DiffRenderOptions ): Promise<{ blob: Blob; changedPercent: number }> { const { width, height, origData, resData } = pair; const { mode, gain, threshold, palette, backgroundDim } = options; const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Не удалось создать буфер карты отличий'); } const out = ctx.createImageData(width, height); const dst = out.data; const lut = mode === 'heatmap' ? buildPaletteLUT(palette) : null; const baseBrightness = 1 - Math.min(0.95, Math.max(0, backgroundDim)); let changedCount = 0; const pixelCount = width * height; for (let i = 0; i < origData.length; i += 4) { const r1 = origData[i]; const g1 = origData[i + 1]; const b1 = origData[i + 2]; const dr = Math.abs(r1 - resData[i]); const dg = Math.abs(g1 - resData[i + 1]); const db = Math.abs(b1 - resData[i + 2]); const maxC = Math.max(dr, dg, db); if (maxC > Math.max(1, threshold)) { changedCount += 1; } if (mode === 'difference') { dst[i] = dr; dst[i + 1] = dg; dst[i + 2] = db; dst[i + 3] = 255; } else if (mode === 'enhanced') { if (maxC <= threshold) { // Subtle darkened context so spatial location remains recognizable dst[i] = Math.round(r1 * 0.14); dst[i + 1] = Math.round(g1 * 0.14); dst[i + 2] = Math.round(b1 * 0.14); dst[i + 3] = 255; } else { const er = Math.min(255, Math.round(Math.max(0, dr - threshold) * gain)); const eg = Math.min(255, Math.round(Math.max(0, dg - threshold) * gain)); const eb = Math.min(255, Math.round(Math.max(0, db - threshold) * gain)); dst[i] = Math.max(er, Math.round(r1 * 0.18)); dst[i + 1] = Math.max(eg, Math.round(g1 * 0.18)); dst[i + 2] = Math.max(eb, Math.round(b1 * 0.18)); dst[i + 3] = 255; } } else if (lut) { // Heatmap over darkened original photo const lum = 0.299 * r1 + 0.587 * g1 + 0.114 * b1; const baseGray = lum * baseBrightness; const avgDiff = (dr + dg + db) / 3; const eff = Math.max(0, avgDiff - threshold); const norm = Math.min(1, (eff * gain) / 255); if (norm <= 0.015) { dst[i] = Math.round(baseGray); dst[i + 1] = Math.round(baseGray); dst[i + 2] = Math.round(baseGray); dst[i + 3] = 255; } else { const idx = Math.min(255, Math.max(0, Math.round(norm * 255))) * 3; const alpha = Math.min(0.92, 0.25 + Math.pow(norm, 0.65) * 0.67); const invAlpha = 1 - alpha; dst[i] = Math.round(baseGray * invAlpha + lut[idx] * alpha); dst[i + 1] = Math.round(baseGray * invAlpha + lut[idx + 1] * alpha); dst[i + 2] = Math.round(baseGray * invAlpha + lut[idx + 2] * alpha); dst[i + 3] = 255; } } } ctx.putImageData(out, 0, 0); const blob = await new Promise((resolve, reject) => { canvas.toBlob( (b) => { if (b) resolve(b); else reject(new Error('Не удалось сформировать карту отличий')); }, 'image/png', 1 ); }); return { blob, changedPercent: (changedCount / Math.max(1, pixelCount)) * 100, }; }