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" />
<title>Convertisseur Images — Matériaux Destock</title>
<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://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<link rel="stylesheet" href="css/app.css" />
@@ -16,21 +15,15 @@
<!-- En-tête -->
<div class="mb-8">
<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>
<!-- ── Zone 1 : Upload ─────────────────────────────────────── -->
<div class="mb-8">
<!-- Tolérance globale -->
<div class="flex items-center gap-4 mb-4">
<label class="text-sm font-medium text-gray-700 whitespace-nowrap">
Tolérance globale :
</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>
<!-- Info modèle IA -->
<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">
<span>🤖</span>
<span>Détourage par IA (WebAssembly) — Le modèle (~40 Mo) se télécharge automatiquement au premier traitement et reste en cache.</span>
</div>
<!-- Zone de dépôt -->
@@ -73,13 +66,27 @@
x-text="{
pending: '⏳ En attente',
converting: '⏳ Conversion…',
processing: '⏳ Détourage…',
processing: '⏳ Détourage IA…',
done: '✅ OK',
error: '❌ Erreur',
}[file.status]">
</span>
</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 -->
<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>
@@ -111,35 +118,16 @@
</div>
</div>
<!-- Contrôles (disponibles une fois le traitement terminé ou en erreur) -->
<!-- Contrôles -->
<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">
<!-- Tolérance individuelle -->
<div class="flex items-center gap-2 text-xs text-gray-600">
<span class="whitespace-nowrap">Tolérance :</span>
<input type="range" min="10" max="80"
x-model.number="file.tolerance"
class="flex-1 accent-blue-500" />
<span class="w-6 text-right font-mono" x-text="file.tolerance"></span>
</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 class="px-3 pb-3 border-t border-gray-100 pt-2">
<button
@click="reprocess(file)"
:disabled="file.status === 'processing'"
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"
>
🔄 Retraiter
</button>
</div>
</template>
@@ -173,186 +161,118 @@
</div><!-- fin x-data -->
<script type="module">
import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3/dist/module.esm.min.js';
import { convertHeicToJpeg } from './js/heicConverter.js';
import { removeBackground, pickColorFromCanvas } from './js/bgRemover.js';
import { processBatch } from './js/imageProcessor.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);
});
}
import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3/dist/module.esm.min.js';
import { convertHeicToJpeg } from './js/heicConverter.js';
import { removeBackground } from './js/bgRemover.js';
import { processBatch } from './js/imageProcessor.js';
import { downloadAllAsZip } from './js/zipExporter.js';
// ── App Alpine.js ──────────────────────────────────────────────
Alpine.data('imageApp', () => ({
files: [],
globalTolerance: 30,
files: [],
get readyCount() {
return this.files.filter(f => f.status === 'done').length;
},
get readyCount() {
return this.files.filter(f => f.status === 'done').length;
},
// ── Tâche 7 : handleFiles ──────────────────────────────────
async handleFiles(fileList) {
const validExts = ['.heic', '.heif'];
const allFiles = Array.from(fileList);
const skipped = allFiles.filter(f =>
!validExts.some(ext => f.name.toLowerCase().endsWith(ext))
async handleFiles(fileList) {
const validExts = ['.heic', '.heif'];
const allFiles = Array.from(fileList);
const skipped = allFiles.filter(f =>
!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) {
alert(
`${skipped.length} fichier(s) ignoré(s) — seuls .heic et .heif sont acceptés.\n` +
`Ignorés : ${skipped.map(f => f.name).join(', ')}`
);
}
const heicFiles = allFiles.filter(f =>
validExts.some(ext => f.name.toLowerCase().endsWith(ext))
);
if (heicFiles.length === 0) return;
const heicFiles = allFiles.filter(f =>
validExts.some(ext => f.name.toLowerCase().endsWith(ext))
);
if (heicFiles.length === 0) return;
const newFiles = heicFiles.map(file => ({
id: crypto.randomUUID(),
name: file.name.replace(/\.[^.]+$/, ''),
status: 'pending',
originalFile: file,
originalBlob: null,
processedBlob: null,
originalUrl: null,
processedUrl: null,
progressLabel: '',
progressPct: 0,
error: null,
}));
const newFiles = heicFiles.map(file => ({
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);
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) => {
// Toujours muter via le proxy réactif d'Alpine
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;
}
// Étape 1 : HEIC → JPEG
f.status = 'converting';
try {
file.processedBlob = await processImage(
file.originalBlob, file._seedColor, file.tolerance
);
file.processedUrl = URL.createObjectURL(file.processedBlob);
file.status = 'done';
f.originalBlob = await convertHeicToJpeg(orig.originalFile);
f.originalUrl = URL.createObjectURL(f.originalBlob);
} catch (e) {
file.status = 'error';
file.error = `Détourage échoué : ${e.message}`;
f.status = 'error';
f.error = `Conversion échouée : ${e.message}`;
return;
}
},
// ── Tâche 8 : startColorPick ───────────────────────────────
async startColorPick(file) {
if (!file.originalUrl) return;
file.pickingColor = true;
// Étape 2 : détourage IA
f.status = 'processing';
f.progressLabel = 'Chargement modèle…';
f.progressPct = 0;
try {
let seedColor;
if (window.EyeDropper) {
// Chrome/Edge : pipette plein écran
seedColor = await pickColorFromCanvas(null);
} else {
// Safari/Firefox : clic sur canvas temporaire
const img = new Image();
await new Promise((res, rej) => {
img.onload = res; img.onerror = rej;
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;
f.processedBlob = await removeBackground(f.originalBlob, ({ key, percent }) => {
f.progressPct = percent;
f.progressLabel = key.includes('model') ? 'Téléchargement modèle IA…' : 'Détourage en cours…';
});
f.processedUrl = URL.createObjectURL(f.processedBlob);
f.status = 'done';
} catch (e) {
f.status = 'error';
f.error = `Détourage échoué : ${e.message}`;
}
},
}, 3);
},
// ── Tâche 9 : downloadAll ──────────────────────────────────
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);
},
async reprocess(file) {
if (!file.originalBlob) return;
file.status = 'processing';
file.error = null;
file.progressLabel = 'Chargement modèle…';
file.progressPct = 0;
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();
+58 -164
View File
@@ -1,178 +1,72 @@
/**
* Distance de Chebyshev entre deux couleurs RGB.
* max(|R1-R2|, |G1-G2|, |B1-B2|)
* @param {number[]} c1 — [R, G, B]
* @param {number[]} c2 — [R, G, B]
* @returns {number}
* Suppression de fond par IA — @imgly/background-removal (WebAssembly).
* Le modèle (~40 Mo) est téléchargé depuis le CDN au premier lancement
* puis mis en cache automatiquement dans le navigateur.
*/
export function chebyshevDistance(c1, c2) {
return Math.max(
Math.abs(c1[0] - c2[0]),
Math.abs(c1[1] - c2[1]),
Math.abs(c1[2] - c2[2])
);
const CDN = 'https://cdn.jsdelivr.net/npm/@imgly/background-removal/dist/';
// Chargement paresseux de la librairie (évite de bloquer le rendu initial)
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
* où 1 = fond, 0 = premier plan.
* @param {{ data: Uint8ClampedArray, width: number, height: number }} imageData
* @param {number[]} seedColor — [R, G, B]
* @param {number} tolerance — tolérance Chebyshev
* @returns {Uint8Array}
* Supprime le fond d'un Blob image via IA.
* Retourne un nouveau Blob JPEG avec fond blanc pur.
* @param {Blob} blob — image source (JPEG)
* @param {function} [onProgress] — callback({ key, percent })
* @returns {Promise<Blob>} Blob JPEG fond blanc
*/
export function createFloodFillMask(imageData, seedColor, tolerance) {
const { data, width, height } = imageData;
const mask = new Uint8Array(width * height);
const visited = new Uint8Array(width * height);
const queue = [];
export async function removeBackground(blob, onProgress) {
const removeBg = await loadLib();
const corners = [0, width - 1, (height - 1) * width, height * width - 1];
for (const idx of corners) {
if (!visited[idx]) { visited[idx] = 1; queue.push(idx); }
}
// Détourage IA → PNG avec transparence
const pngBlob = await removeBg(blob, {
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) {
const idx = queue.pop();
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;
// Composite sur fond blanc → JPEG
return compositeOnWhite(pngBlob);
}
/**
* Remplace les pixels de fond (mask=1) par replacementColor, en place.
* @param {{ data: Uint8ClampedArray }} imageData
* @param {Uint8Array} mask
* @param {number[]} replacementColor — [R, G, B]
* Composite un PNG transparent sur fond blanc, retourne un Blob JPEG.
* @param {Blob} pngBlob
* @returns {Promise<Blob>}
*/
export function applyMaskToImageData(imageData, mask, replacementColor) {
const { data } = imageData;
const [r, g, b] = replacementColor;
for (let i = 0; i < mask.length; i++) {
if (mask[i] === 1) {
const di = i * 4;
data[di] = r; data[di + 1] = g; data[di + 2] = b; data[di + 3] = 255;
}
}
}
/**
* Adoucit la bordure masque/premier-plan en mélangeant sur 1px.
* @param {{ data: Uint8ClampedArray, width: number, height: number }} imageData
* @param {Uint8Array} mask
*/
export function softEdges(imageData, mask) {
const { data, width, height } = imageData;
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);
async function compositeOnWhite(pngBlob) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
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 => {
URL.revokeObjectURL(img.src);
b ? resolve(b) : reject(new Error('canvas.toBlob a retourné null'));
}, 'image/jpeg', 0.92);
};
img.onerror = () => reject(new Error('Impossible de charger le résultat IA'));
img.src = URL.createObjectURL(pngBlob);
});
}