feat: remplacer flood-fill par @imgly/background-removal (IA WebAssembly)
This commit is contained in:
+123
-203
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user