feat: ZIP import, rotation, feather slider, lightbox + config déploiement

- Import ZIP produits (HEIC/JPG/PNG, structure dossiers conservée)
- Rotation des images ±90° avec aperçu CSS et export canvas
- Slider récupération des bords (feather 0–5 px)
- Lightbox plein écran (clic miniature, Échap, fond noir)
- Fix timeout HEIC 30s → 120s
- Fix MIME type blobs JSZip pour heic2any
- Dockerfile nginx:alpine + docker-compose.yml pour déploiement

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-06 11:18:18 +02:00
parent 7f6ca4c3de
commit 86d9b351b1
9 changed files with 368 additions and 81 deletions
+50 -22
View File
@@ -1,13 +1,11 @@
/**
* 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.
* Le modèle est téléchargé depuis staticimgly.com au premier lancement.
*/
const CDN_VERSION = '1.7.0';
const CDN = `https://cdn.jsdelivr.net/npm/@imgly/background-removal@${CDN_VERSION}/dist/`;
// Chargement paresseux de la librairie (évite de bloquer le rendu initial)
let _removeBg = null;
async function loadLib() {
@@ -18,18 +16,17 @@ async function loadLib() {
}
/**
* Supprime le fond d'un Blob image via IA.
* Retourne un nouveau Blob JPEG avec fond blanc pur.
* Supprime le fond d'un Blob image via IA puis composite sur blanc.
* @param {Blob} blob — image source (JPEG)
* @param {function} [onProgress] — callback({ key, percent })
* @param {number} [feather=2] — récupération de bords en px (0 = strict, 5 = doux)
* @returns {Promise<Blob>} Blob JPEG fond blanc
*/
export async function removeBackground(blob, onProgress) {
export async function removeBackground(blob, onProgress, feather = 2) {
const removeBg = await loadLib();
// Détourage IA → PNG avec transparence
const pngBlob = await removeBg(blob, {
// publicPath omis → utilise le CDN par défaut de img.ly (staticimgly.com)
// publicPath omis → utilise staticimgly.com par défaut
output: {
format: 'image/png',
type: 'foreground',
@@ -42,32 +39,63 @@ export async function removeBackground(blob, onProgress) {
},
});
// Composite sur fond blanc → JPEG
return compositeOnWhite(pngBlob);
return compositeOnWhite(pngBlob, feather);
}
/**
* Composite un PNG transparent sur fond blanc, retourne un Blob JPEG.
* Composite un PNG transparent sur fond blanc.
* Si feather > 0, dilate légèrement le contour du sujet (récupère les bords
* que l'IA a pu couper trop agressivement).
* @param {Blob} pngBlob
* @returns {Promise<Blob>}
* @param {number} feather — rayon de dilation en pixels (05)
* @returns {Promise<Blob>} JPEG fond blanc
*/
async function compositeOnWhite(pngBlob) {
async function compositeOnWhite(pngBlob, feather) {
const objectUrl = URL.createObjectURL(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');
const { width, height } = img;
// ── Canvas intermédiaire : premier plan avec bords optionnels ──
const fgCanvas = document.createElement('canvas');
fgCanvas.width = width;
fgCanvas.height = height;
const fgCtx = fgCanvas.getContext('2d');
// 1. Dessin net du premier plan
fgCtx.drawImage(img, 0, 0);
if (feather > 0) {
// 2. On dessine une version floutée DERRIÈRE le dessin net
// (destination-over = "derrière le contenu existant")
// → les zones transparentes proches des bords du sujet deviennent
// semi-transparentes, récupérant les détails coupés par l'IA.
fgCtx.globalCompositeOperation = 'destination-over';
fgCtx.filter = `blur(${feather}px)`;
fgCtx.drawImage(img, 0, 0);
fgCtx.filter = 'none';
fgCtx.globalCompositeOperation = 'source-over';
}
// ── Canvas final : fond blanc + premier plan ───────────────────
const out = document.createElement('canvas');
out.width = width;
out.height = height;
const ctx = out.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);
ctx.fillRect(0, 0, width, height);
ctx.drawImage(fgCanvas, 0, 0);
URL.revokeObjectURL(objectUrl);
out.toBlob(b => {
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);
img.src = objectUrl;
});
}
+15 -12
View File
@@ -1,28 +1,31 @@
/**
* Convertit un fichier HEIC/HEIF en Blob JPEG.
* @param {File} file
* Convertit un fichier/blob HEIC/HEIF en Blob JPEG.
* @param {File|Blob} fileOrBlob — fichier HEIC/HEIF (File depuis l'input, ou Blob extrait d'un ZIP)
* @returns {Promise<Blob>}
* @throws {TypeError} si l'entrée n'est pas un fichier HEIC/HEIF
* @throws {TypeError} si l'entrée n'est pas un Blob HEIC/HEIF
* @throws {Error} si la conversion échoue ou dépasse 30s
*/
export async function convertHeicToJpeg(file) {
if (!(file instanceof File)) {
throw new TypeError("L'entrée doit être un objet File");
export async function convertHeicToJpeg(fileOrBlob) {
if (!(fileOrBlob instanceof Blob)) {
throw new TypeError("L'entrée doit être un Blob ou un File");
}
// Certains iPhone envoient un type MIME vide pour les HEIC — on l'autorise
const type = file.type.toLowerCase();
const type = fileOrBlob.type.toLowerCase();
if (type !== '' && !['image/heic', 'image/heif'].includes(type)) {
throw new TypeError(`Format attendu : HEIC/HEIF. Reçu : ${file.type || '(vide)'}`);
throw new TypeError(`Format attendu : HEIC/HEIF. Reçu : ${fileOrBlob.type || '(vide)'}`);
}
console.log(`[heicConverter] Début conversion : ${file.name} (${file.type || 'type vide'}, ${(file.size/1024).toFixed(0)} Ko)`);
const label = fileOrBlob instanceof File
? `${fileOrBlob.name} (${fileOrBlob.type || 'type vide'}, ${(fileOrBlob.size / 1024).toFixed(0)} Ko)`
: `blob HEIC (${(fileOrBlob.size / 1024).toFixed(0)} Ko)`;
console.log(`[heicConverter] Début conversion : ${label}`);
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout : conversion > 30s. Vérifiez que le fichier est bien un HEIC valide.')), 30_000)
setTimeout(() => reject(new Error('Timeout : conversion > 120s. Vérifiez que le fichier est bien un HEIC valide.')), 120_000)
);
const conversion = heic2any({
blob: file,
blob: fileOrBlob,
toType: 'image/jpeg',
quality: 0.92,
});
@@ -34,6 +37,6 @@ export async function convertHeicToJpeg(file) {
throw new Error("heic2any n'a pas retourné un Blob");
}
console.log(`[heicConverter] ✅ Conversion réussie : ${file.name}${(blob.size/1024).toFixed(0)} Ko`);
console.log(`[heicConverter] ✅ Conversion réussie → ${(blob.size / 1024).toFixed(0)} Ko`);
return blob;
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Rotation d'un Blob image via Canvas.
* @param {Blob} blob — image source (JPEG)
* @param {number} degrees — angle de rotation en degrés (0, 90, 180, 270)
* @returns {Promise<Blob>} Blob JPEG pivoté, ou le blob original si degrees === 0
*/
export async function rotateBlob(blob, degrees) {
const norm = ((degrees % 360) + 360) % 360;
if (norm === 0) return blob;
const url = URL.createObjectURL(blob);
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
// Pour 90° ou 270°, largeur et hauteur sont inversées
const swap = norm === 90 || norm === 270;
const w = swap ? img.naturalHeight : img.naturalWidth;
const h = swap ? img.naturalWidth : img.naturalHeight;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.translate(w / 2, h / 2);
ctx.rotate((norm * Math.PI) / 180);
ctx.drawImage(img, -img.naturalWidth / 2, -img.naturalHeight / 2);
URL.revokeObjectURL(url);
canvas.toBlob(
b => b ? resolve(b) : reject(new Error('rotateBlob : toBlob a retourné null')),
'image/jpeg',
0.92
);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('rotateBlob : impossible de charger le blob'));
};
img.src = url;
});
}
+5 -3
View File
@@ -1,12 +1,14 @@
/**
* Compresse les fichiers en ZIP et déclenche le téléchargement.
* @param {{ name: string, blob: Blob }[]} processedFiles
* Si un fichier possède un `folder`, il est placé dans le sous-dossier correspondant.
* @param {{ name: string, blob: Blob, folder?: string }[]} processedFiles
* @returns {Promise<void>}
*/
export async function downloadAllAsZip(processedFiles) {
const zip = new JSZip();
for (const { name, blob } of processedFiles) {
zip.file(name, blob);
for (const { name, blob, folder } of processedFiles) {
const path = folder ? `${folder}/${name}` : name;
zip.file(path, blob);
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(zipBlob);
+57
View File
@@ -0,0 +1,57 @@
/**
* Lecture d'un ZIP produits.
* Attend une structure : dossier-produit/image.heic (ou jpg/png).
* JSZip est chargé comme script global dans index.html.
*/
const IMAGE_EXTS = new Set(['heic', 'heif', 'jpg', 'jpeg', 'png']);
/**
* Extrait toutes les images d'un fichier ZIP.
* @param {File} zipFile
* @returns {Promise<Array<{folder:string, name:string, ext:string, blob:Blob, isHeic:boolean}>>}
*/
export async function readImagesFromZip(zipFile) {
const zip = await JSZip.loadAsync(zipFile);
// Collecter les entrées fichier (pas les dossiers)
const entries = [];
zip.forEach((relativePath, entry) => {
if (!entry.dir) entries.push({ relativePath, entry });
});
const results = [];
for (const { relativePath, entry } of entries) {
// Ignorer les métadonnées macOS et fichiers cachés
if (relativePath.startsWith('__MACOSX/')) continue;
const parts = relativePath.split('/').filter(p => p.length > 0);
const filename = parts[parts.length - 1];
if (filename.startsWith('.')) continue;
// Extension
const dotIdx = filename.lastIndexOf('.');
if (dotIdx === -1) continue;
const ext = filename.slice(dotIdx + 1).toLowerCase();
if (!IMAGE_EXTS.has(ext)) continue;
const name = filename.slice(0, dotIdx);
// Premier segment du chemin = dossier produit (ex: "12345")
const folder = parts.length > 1 ? parts[0] : '';
const isHeic = ext === 'heic' || ext === 'heif';
const mimeType = isHeic ? 'image/heic'
: (ext === 'jpg' || ext === 'jpeg') ? 'image/jpeg'
: 'image/png';
// JSZip retourne des Blobs sans type MIME — on le définit explicitement
// pour que heic2any puisse détecter le format correctement.
const rawBlob = await entry.async('blob');
const blob = new Blob([rawBlob], { type: mimeType });
results.push({ folder, name, ext, blob, isHeic });
}
return results;
}