feat: remplacer flood-fill par @imgly/background-removal (IA WebAssembly)

This commit is contained in:
2026-05-27 10:33:31 +02:00
parent 8fe75db238
commit 7e2bbfcca2
2 changed files with 181 additions and 367 deletions
+123 -203
View File
@@ -5,7 +5,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Convertisseur Images — Matériaux Destock</title> <title>Convertisseur Images — Matériaux Destock</title>
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<!-- Alpine chargé comme module ES pour contrôler le timing d'initialisation -->
<script src="https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<link rel="stylesheet" href="css/app.css" /> <link rel="stylesheet" href="css/app.css" />
@@ -16,21 +15,15 @@
<!-- En-tête --> <!-- En-tête -->
<div class="mb-8"> <div class="mb-8">
<h1 class="text-2xl font-bold text-gray-800">Convertisseur Images Shopify</h1> <h1 class="text-2xl font-bold text-gray-800">Convertisseur Images Shopify</h1>
<p class="text-gray-500 text-sm mt-1">HEIC → JPG · Suppression fond blanc · Export ZIP</p> <p class="text-gray-500 text-sm mt-1">HEIC → JPG · Détourage IA · Export ZIP</p>
</div> </div>
<!-- ── Zone 1 : Upload ─────────────────────────────────────── --> <!-- ── Zone 1 : Upload ─────────────────────────────────────── -->
<div class="mb-8"> <div class="mb-8">
<!-- Tolérance globale --> <!-- Info modèle IA -->
<div class="flex items-center gap-4 mb-4"> <div class="flex items-center gap-2 mb-4 text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded-lg px-3 py-2">
<label class="text-sm font-medium text-gray-700 whitespace-nowrap"> <span>🤖</span>
Tolérance globale : <span>Détourage par IA (WebAssembly) — Le modèle (~40 Mo) se télécharge automatiquement au premier traitement et reste en cache.</span>
</label>
<input type="range" min="10" max="80"
x-model.number="globalTolerance"
class="w-48 accent-blue-500" />
<span class="text-sm font-mono text-gray-600 w-8" x-text="globalTolerance"></span>
<span class="text-xs text-gray-400">(10 = strict · 80 = permissif)</span>
</div> </div>
<!-- Zone de dépôt --> <!-- Zone de dépôt -->
@@ -73,13 +66,27 @@
x-text="{ x-text="{
pending: '⏳ En attente', pending: '⏳ En attente',
converting: '⏳ Conversion…', converting: '⏳ Conversion…',
processing: '⏳ Détourage…', processing: '⏳ Détourage IA…',
done: '✅ OK', done: '✅ OK',
error: '❌ Erreur', error: '❌ Erreur',
}[file.status]"> }[file.status]">
</span> </span>
</div> </div>
<!-- Progression IA (visible pendant le détourage) -->
<template x-if="file.status === 'processing' && file.progressLabel">
<div class="px-4 py-2 bg-blue-50 border-b border-blue-100">
<div class="flex items-center justify-between text-xs text-blue-700 mb-1">
<span x-text="file.progressLabel"></span>
<span x-text="file.progressPct + '%'"></span>
</div>
<div class="w-full bg-blue-200 rounded-full h-1.5">
<div class="bg-blue-500 h-1.5 rounded-full transition-all duration-200"
:style="'width:' + file.progressPct + '%'"></div>
</div>
</div>
</template>
<!-- Message d'erreur --> <!-- Message d'erreur -->
<template x-if="file.status === 'error'"> <template x-if="file.status === 'error'">
<div class="px-4 py-3 text-sm text-red-600 bg-red-50" x-text="file.error"></div> <div class="px-4 py-3 text-sm text-red-600 bg-red-50" x-text="file.error"></div>
@@ -111,35 +118,16 @@
</div> </div>
</div> </div>
<!-- Contrôles (disponibles une fois le traitement terminé ou en erreur) --> <!-- Contrôles -->
<template x-if="file.status === 'done' || file.status === 'error'"> <template x-if="file.status === 'done' || file.status === 'error'">
<div class="px-3 pb-3 space-y-2 border-t border-gray-100 pt-2"> <div class="px-3 pb-3 border-t border-gray-100 pt-2">
<!-- Tolérance individuelle --> <button
<div class="flex items-center gap-2 text-xs text-gray-600"> @click="reprocess(file)"
<span class="whitespace-nowrap">Tolérance :</span> :disabled="file.status === 'processing'"
<input type="range" min="10" max="80" class="w-full text-xs bg-blue-50 hover:bg-blue-100 disabled:opacity-50 text-blue-700 border border-blue-200 rounded-lg py-1.5 px-2 transition-colors"
x-model.number="file.tolerance" >
class="flex-1 accent-blue-500" /> 🔄 Retraiter
<span class="w-6 text-right font-mono" x-text="file.tolerance"></span> </button>
</div>
<!-- Boutons d'action -->
<div class="flex gap-2">
<button
@click="startColorPick(file)"
:disabled="file.pickingColor"
class="flex-1 text-xs bg-purple-50 hover:bg-purple-100 disabled:opacity-50 text-purple-700 border border-purple-200 rounded-lg py-1.5 px-2 transition-colors"
:class="{ 'ring-2 ring-purple-400': file.pickingColor }"
>
🎨 Pipette
</button>
<button
@click="reprocess(file)"
:disabled="file.status === 'processing'"
class="flex-1 text-xs bg-blue-50 hover:bg-blue-100 disabled:opacity-50 text-blue-700 border border-blue-200 rounded-lg py-1.5 px-2 transition-colors"
>
🔄 Retraiter
</button>
</div>
</div> </div>
</template> </template>
@@ -173,186 +161,118 @@
</div><!-- fin x-data --> </div><!-- fin x-data -->
<script type="module"> <script type="module">
import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3/dist/module.esm.min.js'; import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3/dist/module.esm.min.js';
import { convertHeicToJpeg } from './js/heicConverter.js'; import { convertHeicToJpeg } from './js/heicConverter.js';
import { removeBackground, pickColorFromCanvas } from './js/bgRemover.js'; import { removeBackground } from './js/bgRemover.js';
import { processBatch } from './js/imageProcessor.js'; import { processBatch } from './js/imageProcessor.js';
import { downloadAllAsZip } from './js/zipExporter.js'; import { downloadAllAsZip } from './js/zipExporter.js';
// ── Helper : Blob → canvas → fond supprimé → Blob JPEG ────────
async function processImage(blob, seedColor, tolerance) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
try {
removeBackground(canvas, seedColor ?? null, tolerance);
canvas.toBlob(b => {
URL.revokeObjectURL(img.src);
b ? resolve(b) : reject(new Error('canvas.toBlob a retourné null'));
}, 'image/jpeg', 0.92);
} catch (e) {
reject(e);
}
};
img.onerror = () => reject(new Error("Impossible de charger l'image"));
img.src = URL.createObjectURL(blob);
});
}
// ── App Alpine.js ────────────────────────────────────────────── // ── App Alpine.js ──────────────────────────────────────────────
Alpine.data('imageApp', () => ({ Alpine.data('imageApp', () => ({
files: [], files: [],
globalTolerance: 30,
get readyCount() { get readyCount() {
return this.files.filter(f => f.status === 'done').length; return this.files.filter(f => f.status === 'done').length;
}, },
// ── Tâche 7 : handleFiles ────────────────────────────────── async handleFiles(fileList) {
async handleFiles(fileList) { const validExts = ['.heic', '.heif'];
const validExts = ['.heic', '.heif']; const allFiles = Array.from(fileList);
const allFiles = Array.from(fileList); const skipped = allFiles.filter(f =>
const skipped = allFiles.filter(f => !validExts.some(ext => f.name.toLowerCase().endsWith(ext))
!validExts.some(ext => f.name.toLowerCase().endsWith(ext)) );
if (skipped.length > 0) {
alert(
`${skipped.length} fichier(s) ignoré(s) — seuls .heic et .heif sont acceptés.\n` +
`Ignorés : ${skipped.map(f => f.name).join(', ')}`
); );
}
if (skipped.length > 0) { const heicFiles = allFiles.filter(f =>
alert( validExts.some(ext => f.name.toLowerCase().endsWith(ext))
`${skipped.length} fichier(s) ignoré(s) — seuls .heic et .heif sont acceptés.\n` + );
`Ignorés : ${skipped.map(f => f.name).join(', ')}` if (heicFiles.length === 0) return;
);
}
const heicFiles = allFiles.filter(f => const newFiles = heicFiles.map(file => ({
validExts.some(ext => f.name.toLowerCase().endsWith(ext)) id: crypto.randomUUID(),
); name: file.name.replace(/\.[^.]+$/, ''),
if (heicFiles.length === 0) return; status: 'pending',
originalFile: file,
originalBlob: null,
processedBlob: null,
originalUrl: null,
processedUrl: null,
progressLabel: '',
progressPct: 0,
error: null,
}));
const newFiles = heicFiles.map(file => ({ this.files.push(...newFiles);
id: crypto.randomUUID(),
name: file.name.replace(/\.[^.]+$/, ''), // supprime l'extension
status: 'pending',
originalFile: file,
originalBlob: null,
processedBlob: null,
originalUrl: null,
processedUrl: null,
tolerance: this.globalTolerance,
_seedColor: null, // défini par la pipette
error: null,
pickingColor: false,
}));
this.files.push(...newFiles); await processBatch(newFiles, async (orig) => {
const f = this.files.find(x => x.id === orig.id);
if (!f) return;
await processBatch(newFiles, async (orig) => { // Étape 1 : HEIC → JPEG
// Toujours muter via le proxy réactif d'Alpine f.status = 'converting';
const f = this.files.find(x => x.id === orig.id);
if (!f) return;
// Étape 1 : HEIC → JPEG
f.status = 'converting';
try {
f.originalBlob = await convertHeicToJpeg(orig.originalFile);
f.originalUrl = URL.createObjectURL(f.originalBlob);
} catch (e) {
f.status = 'error';
f.error = `Conversion échouée : ${e.message}`;
return;
}
// Étape 2 : suppression du fond
f.status = 'processing';
try {
f.processedBlob = await processImage(
f.originalBlob, f._seedColor, f.tolerance
);
f.processedUrl = URL.createObjectURL(f.processedBlob);
f.status = 'done';
} catch (e) {
f.status = 'error';
f.error = `Détourage échoué : ${e.message}`;
}
}, 3);
},
// ── Tâche 8 : reprocess ────────────────────────────────────
async reprocess(file) {
if (!file.originalBlob) return;
file.status = 'processing';
file.error = null;
if (file.processedUrl) {
URL.revokeObjectURL(file.processedUrl);
file.processedUrl = null;
}
try { try {
file.processedBlob = await processImage( f.originalBlob = await convertHeicToJpeg(orig.originalFile);
file.originalBlob, file._seedColor, file.tolerance f.originalUrl = URL.createObjectURL(f.originalBlob);
);
file.processedUrl = URL.createObjectURL(file.processedBlob);
file.status = 'done';
} catch (e) { } catch (e) {
file.status = 'error'; f.status = 'error';
file.error = `Détourage échoué : ${e.message}`; f.error = `Conversion échouée : ${e.message}`;
return;
} }
},
// ── Tâche 8 : startColorPick ─────────────────────────────── // Étape 2 : détourage IA
async startColorPick(file) { f.status = 'processing';
if (!file.originalUrl) return; f.progressLabel = 'Chargement modèle…';
file.pickingColor = true; f.progressPct = 0;
try { try {
let seedColor; f.processedBlob = await removeBackground(f.originalBlob, ({ key, percent }) => {
if (window.EyeDropper) { f.progressPct = percent;
// Chrome/Edge : pipette plein écran f.progressLabel = key.includes('model') ? 'Téléchargement modèle IA…' : 'Détourage en cours…';
seedColor = await pickColorFromCanvas(null); });
} else { f.processedUrl = URL.createObjectURL(f.processedBlob);
// Safari/Firefox : clic sur canvas temporaire f.status = 'done';
const img = new Image(); } catch (e) {
await new Promise((res, rej) => { f.status = 'error';
img.onload = res; img.onerror = rej; f.error = `Détourage échoué : ${e.message}`;
img.src = file.originalUrl;
});
const tempCanvas = document.createElement('canvas');
tempCanvas.width = img.width;
tempCanvas.height = img.height;
tempCanvas.getContext('2d').drawImage(img, 0, 0);
tempCanvas.style.cssText =
'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);' +
'max-width:80vw;max-height:80vh;z-index:9999;border:3px solid #7c3aed;';
const overlay = document.createElement('div');
overlay.style.cssText =
'position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9998;';
const hint = document.createElement('p');
hint.style.cssText =
'position:fixed;bottom:10%;left:50%;transform:translateX(-50%);' +
'color:white;background:#7c3aed;padding:8px 16px;border-radius:8px;z-index:10000;font-family:sans-serif;';
hint.textContent = 'Cliquez sur la couleur de fond à supprimer';
document.body.append(overlay, tempCanvas, hint);
seedColor = await pickColorFromCanvas(tempCanvas);
overlay.remove(); tempCanvas.remove(); hint.remove();
}
file._seedColor = seedColor;
await this.reprocess(file);
} catch {
// Utilisateur a annulé — pas d'action
} finally {
file.pickingColor = false;
} }
}, }, 3);
},
// ── Tâche 9 : downloadAll ────────────────────────────────── async reprocess(file) {
async downloadAll() { if (!file.originalBlob) return;
const readyFiles = this.files file.status = 'processing';
.filter(f => f.status === 'done' && f.processedBlob) file.error = null;
.map(f => ({ name: `${f.name}.jpg`, blob: f.processedBlob })); file.progressLabel = 'Chargement modèle…';
if (readyFiles.length === 0) return; file.progressPct = 0;
await downloadAllAsZip(readyFiles); if (file.processedUrl) {
}, URL.revokeObjectURL(file.processedUrl);
file.processedUrl = null;
}
try {
file.processedBlob = await removeBackground(file.originalBlob, ({ key, percent }) => {
file.progressPct = percent;
file.progressLabel = key.includes('model') ? 'Téléchargement modèle IA…' : 'Détourage en cours…';
});
file.processedUrl = URL.createObjectURL(file.processedBlob);
file.status = 'done';
} catch (e) {
file.status = 'error';
file.error = `Détourage échoué : ${e.message}`;
}
},
async downloadAll() {
const readyFiles = this.files
.filter(f => f.status === 'done' && f.processedBlob)
.map(f => ({ name: `${f.name}.jpg`, blob: f.processedBlob }));
if (readyFiles.length === 0) return;
await downloadAllAsZip(readyFiles);
},
})); }));
Alpine.start(); Alpine.start();
+58 -164
View File
@@ -1,178 +1,72 @@
/** /**
* Distance de Chebyshev entre deux couleurs RGB. * Suppression de fond par IA — @imgly/background-removal (WebAssembly).
* max(|R1-R2|, |G1-G2|, |B1-B2|) * Le modèle (~40 Mo) est téléchargé depuis le CDN au premier lancement
* @param {number[]} c1 — [R, G, B] * puis mis en cache automatiquement dans le navigateur.
* @param {number[]} c2 — [R, G, B]
* @returns {number}
*/ */
export function chebyshevDistance(c1, c2) {
return Math.max( const CDN = 'https://cdn.jsdelivr.net/npm/@imgly/background-removal/dist/';
Math.abs(c1[0] - c2[0]),
Math.abs(c1[1] - c2[1]), // Chargement paresseux de la librairie (évite de bloquer le rendu initial)
Math.abs(c1[2] - c2[2]) let _removeBg = null;
);
async function loadLib() {
if (_removeBg) return _removeBg;
const mod = await import(CDN + 'bundle.browser.esm.js');
_removeBg = mod.removeBackground;
return _removeBg;
} }
/** /**
* Flood-fill BFS depuis les 4 coins. Retourne un masque Uint8Array * Supprime le fond d'un Blob image via IA.
* où 1 = fond, 0 = premier plan. * Retourne un nouveau Blob JPEG avec fond blanc pur.
* @param {{ data: Uint8ClampedArray, width: number, height: number }} imageData * @param {Blob} blob — image source (JPEG)
* @param {number[]} seedColor — [R, G, B] * @param {function} [onProgress] — callback({ key, percent })
* @param {number} tolerance — tolérance Chebyshev * @returns {Promise<Blob>} Blob JPEG fond blanc
* @returns {Uint8Array}
*/ */
export function createFloodFillMask(imageData, seedColor, tolerance) { export async function removeBackground(blob, onProgress) {
const { data, width, height } = imageData; const removeBg = await loadLib();
const mask = new Uint8Array(width * height);
const visited = new Uint8Array(width * height);
const queue = [];
const corners = [0, width - 1, (height - 1) * width, height * width - 1]; // Détourage IA → PNG avec transparence
for (const idx of corners) { const pngBlob = await removeBg(blob, {
if (!visited[idx]) { visited[idx] = 1; queue.push(idx); } publicPath: CDN,
} output: {
format: 'image/png',
type: 'foreground',
quality: 1,
},
progress: (key, current, total) => {
if (onProgress && total > 0) {
onProgress({ key, percent: Math.round((current / total) * 100) });
}
},
});
while (queue.length > 0) { // Composite sur fond blanc → JPEG
const idx = queue.pop(); return compositeOnWhite(pngBlob);
const di = idx * 4;
const px = [data[di], data[di + 1], data[di + 2]];
if (chebyshevDistance(px, seedColor) > tolerance) continue;
mask[idx] = 1;
const x = idx % width;
const y = Math.floor(idx / width);
const neighbors = [
x > 0 ? idx - 1 : -1,
x < width-1 ? idx + 1 : -1,
y > 0 ? idx - width : -1,
y < height-1 ? idx + width : -1,
];
for (const n of neighbors) {
if (n >= 0 && !visited[n]) { visited[n] = 1; queue.push(n); }
}
}
return mask;
} }
/** /**
* Remplace les pixels de fond (mask=1) par replacementColor, en place. * Composite un PNG transparent sur fond blanc, retourne un Blob JPEG.
* @param {{ data: Uint8ClampedArray }} imageData * @param {Blob} pngBlob
* @param {Uint8Array} mask * @returns {Promise<Blob>}
* @param {number[]} replacementColor — [R, G, B]
*/ */
export function applyMaskToImageData(imageData, mask, replacementColor) { async function compositeOnWhite(pngBlob) {
const { data } = imageData; return new Promise((resolve, reject) => {
const [r, g, b] = replacementColor; const img = new Image();
for (let i = 0; i < mask.length; i++) { img.onload = () => {
if (mask[i] === 1) { const canvas = document.createElement('canvas');
const di = i * 4; canvas.width = img.width;
data[di] = r; data[di + 1] = g; data[di + 2] = b; data[di + 3] = 255; canvas.height = img.height;
} const ctx = canvas.getContext('2d');
} ctx.fillStyle = '#ffffff';
} ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
/** canvas.toBlob(b => {
* Adoucit la bordure masque/premier-plan en mélangeant sur 1px. URL.revokeObjectURL(img.src);
* @param {{ data: Uint8ClampedArray, width: number, height: number }} imageData b ? resolve(b) : reject(new Error('canvas.toBlob a retourné null'));
* @param {Uint8Array} mask }, 'image/jpeg', 0.92);
*/ };
export function softEdges(imageData, mask) { img.onerror = () => reject(new Error('Impossible de charger le résultat IA'));
const { data, width, height } = imageData; img.src = URL.createObjectURL(pngBlob);
const total = width * height;
const edgePixels = [];
for (let i = 0; i < total; i++) {
if (mask[i] !== 1) continue;
const x = i % width, y = Math.floor(i / width);
const neighbors = [
x > 0 ? i - 1 : -1,
x < width-1 ? i + 1 : -1,
y > 0 ? i - width : -1,
y < height-1 ? i + width : -1,
];
if (neighbors.some(n => n >= 0 && mask[n] === 0)) edgePixels.push(i);
}
for (const i of edgePixels) {
const x = i % width, y = Math.floor(i / width);
const fgNeighbors = [
x > 0 ? i - 1 : -1,
x < width-1 ? i + 1 : -1,
y > 0 ? i - width : -1,
y < height-1 ? i + width : -1,
].filter(n => n >= 0 && mask[n] === 0);
if (fgNeighbors.length === 0) continue;
let sR = 0, sG = 0, sB = 0;
for (const n of fgNeighbors) {
sR += data[n * 4]; sG += data[n * 4 + 1]; sB += data[n * 4 + 2];
}
const di = i * 4, c = fgNeighbors.length;
data[di] = Math.round((data[di] + sR / c) / 2);
data[di + 1] = Math.round((data[di + 1] + sG / c) / 2);
data[di + 2] = Math.round((data[di + 2] + sB / c) / 2);
}
}
/**
* Supprime le fond d'un canvas en place.
* @param {HTMLCanvasElement} canvas
* @param {number[]|null} seedColor — [R,G,B]; si null, utilise le coin haut-gauche
* @param {number} tolerance
* @throws {Error} si aucun pixel de fond n'est détecté
*/
export function removeBackground(canvas, seedColor = null, tolerance = 30) {
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const seed = seedColor ?? [imageData.data[0], imageData.data[1], imageData.data[2]];
const mask = createFloodFillMask(imageData, seed, tolerance);
const maskedCount = mask.reduce((a, b) => a + b, 0);
if (maskedCount === 0) {
throw new Error(
"Aucun fond détecté. Augmentez la tolérance ou utilisez la pipette."
);
}
applyMaskToImageData(imageData, mask, [255, 255, 255]);
softEdges(imageData, mask);
ctx.putImageData(imageData, 0, 0);
}
/**
* Laisse l'utilisateur choisir une couleur.
* Chrome/Edge : EyeDropper API (plein écran).
* Safari/Firefox : clic sur le canvas fourni.
* @param {HTMLCanvasElement|null} canvas — requis uniquement en fallback Safari
* @returns {Promise<number[]>} [R, G, B]
*/
export async function pickColorFromCanvas(canvas) {
if (window.EyeDropper) {
const dropper = new window.EyeDropper();
const result = await dropper.open(); // { sRGBHex: "#rrggbb" }
const hex = result.sRGBHex.replace('#', '');
return [
parseInt(hex.slice(0, 2), 16),
parseInt(hex.slice(2, 4), 16),
parseInt(hex.slice(4, 6), 16),
];
}
if (!canvas) throw new Error('Canvas requis pour la pipette sur ce navigateur');
return new Promise((resolve) => {
canvas.classList.add('picking-color');
function onClick(e) {
canvas.removeEventListener('click', onClick);
canvas.classList.remove('picking-color');
const rect = canvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) * (canvas.width / rect.width));
const y = Math.floor((e.clientY - rect.top) * (canvas.height / rect.height));
const pixel = canvas.getContext('2d').getImageData(x, y, 1, 1).data;
resolve([pixel[0], pixel[1], pixel[2]]);
}
canvas.addEventListener('click', onClick);
}); });
} }