API d'utilitaires
Sharp fournit diverses fonctions utilitaires pour faciliter le traitement d'image et la conversion de format.
Détection de format
Détecter les formats supportés
javascript
import sharp from 'sharp';
// Obtenir les formats d'entrée supportés
console.log('Formats d'entrée supportés:', sharp.format);
// Obtenir les formats de sortie supportés
console.log('Formats de sortie supportés:', sharp.format);Vérifier le format de fichier
javascript
async function checkImageFormat(filePath) {
try {
const metadata = await sharp(filePath).metadata();
return {
format: metadata.format,
width: metadata.width,
height: metadata.height,
channels: metadata.channels
};
} catch (error) {
return { error: error.message };
}
}Espace colorimétrique
Constantes d'espace colorimétrique
javascript
// Espaces colorimétriques disponibles
sharp.colourspace.srgb // sRGB
sharp.colourspace.rgb // RGB
sharp.colourspace.cmyk // CMYK
sharp.colourspace.grey // Niveaux de gris
sharp.colourspace.multiband // Multi-bandes
sharp.colourspace.lab // Lab
sharp.colourspace.xyz // XYZ
sharp.colourspace.ycbcr // YCbCrConversion d'espace colorimétrique
javascript
// Convertir en niveaux de gris
sharp('input.jpg')
.grayscale()
.toFile('output.jpg');
// Convertir en CMYK
sharp('input.jpg')
.toColourspace(sharp.colourspace.cmyk)
.tiff()
.toFile('output.tiff');Noyaux et filtres
Noyaux de redimensionnement
javascript
// Noyaux de redimensionnement disponibles
sharp.kernel.nearest // Plus proche voisin
sharp.kernel.cubic // Interpolation cubique
sharp.kernel.mitchell // Mitchell-Netravali
sharp.kernel.lanczos2 // Lanczos 2-lobed
sharp.kernel.lanczos3 // Lanczos 3-lobed (par défaut)Utiliser des noyaux personnalisés
javascript
// Utiliser un noyau de redimensionnement personnalisé
sharp('input.jpg')
.resize(300, 200, { kernel: sharp.kernel.lanczos3 })
.toFile('output.jpg');Constantes de position
Options de position
javascript
// Options de position disponibles
sharp.position.top // Haut
sharp.position.right // Droite
sharp.position.bottom // Bas
sharp.position.left // Gauche
sharp.position.center // Centre (par défaut)
sharp.position.centre // Centre (orthographe britannique)
sharp.position.north // Nord (haut)
sharp.position.east // Est (droite)
sharp.position.south // Sud (bas)
sharp.position.west // Ouest (gauche)
sharp.position.northeast // Nord-est
sharp.position.southeast // Sud-est
sharp.position.southwest // Sud-ouest
sharp.position.northwest // Nord-ouestOpérations de canaux
Constantes de canaux
javascript
// Constantes de canaux
sharp.channel.red // Canal rouge
sharp.channel.green // Canal vert
sharp.channel.blue // Canal bleu
sharp.channel.alpha // Canal alpha
sharp.channel.grey // Canal grisOpérations de canaux
javascript
// Extraire le canal rouge
sharp('input.jpg')
.extractChannel(sharp.channel.red)
.toFile('red-channel.jpg');
// Extraire tous les canaux
const channels = await sharp('input.jpg').separate();Gestion des erreurs
Types d'erreurs
javascript
// Erreurs Sharp courantes
sharp.errors.InputError // Erreur d'entrée
sharp.errors.ProcessError // Erreur de traitement
sharp.errors.OutputError // Erreur de sortieExemple de gestion des erreurs
javascript
try {
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
} catch (error) {
if (error instanceof sharp.errors.InputError) {
console.error('Erreur de fichier d'entrée:', error.message);
} else if (error instanceof sharp.errors.ProcessError) {
console.error('Erreur de traitement:', error.message);
} else if (error instanceof sharp.errors.OutputError) {
console.error('Erreur de sortie:', error.message);
} else {
console.error('Erreur inconnue:', error.message);
}
}Surveillance des performances
Utilisation de la mémoire
javascript
// Obtenir les statistiques d'utilisation de la mémoire Sharp
const stats = sharp.cache();
console.log('Statistiques du cache:', stats);
// Vider le cache
sharp.cache(false);Contrôle de la concurrence
javascript
// Définir la limite de concurrence
sharp.concurrency(4); // Maximum 4 opérations simultanées
// Obtenir le nombre de concurrences actuel
console.log('Concurrence actuelle:', sharp.concurrency());Fonctions utilitaires
Créer une image de test
javascript
// Créer une image unie
const redImage = sharp({
create: {
width: 300,
height: 200,
channels: 3,
background: { r: 255, g: 0, b: 0 }
}
});
// Créer une image dégradée
const gradient = sharp({
create: {
width: 300,
height: 200,
channels: 3,
background: { r: 0, g: 0, b: 0 }
}
});Composition d'images
javascript
// Composer plusieurs images
const composite = await sharp('background.jpg')
.composite([
{
input: 'overlay.png',
top: 100,
left: 100
}
])
.jpeg()
.toBuffer();Outils de traitement par lot
Redimensionnement par lot
javascript
const fs = require('fs').promises;
async function batchResize(inputDir, outputDir, width, height) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
await sharp(`${inputDir}/${file}`)
.resize(width, height)
.jpeg({ quality: 80 })
.toFile(`${outputDir}/${file}`);
console.log(`Traitement terminé: ${file}`);
} catch (error) {
console.error(`Échec du traitement ${file}:`, error.message);
}
}
}
}Conversion de format par lot
javascript
async function batchConvert(inputDir, outputDir, format) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
const outputFile = file.replace(/\.[^.]+$/, `.${format}`);
try {
const image = sharp(`${inputDir}/${file}`);
switch (format) {
case 'jpg':
case 'jpeg':
await image.jpeg({ quality: 80 }).toFile(`${outputDir}/${outputFile}`);
break;
case 'png':
await image.png().toFile(`${outputDir}/${outputFile}`);
break;
case 'webp':
await image.webp({ quality: 80 }).toFile(`${outputDir}/${outputFile}`);
break;
case 'avif':
await image.avif({ quality: 80 }).toFile(`${outputDir}/${outputFile}`);
break;
}
console.log(`Conversion terminée: ${file} -> ${outputFile}`);
} catch (error) {
console.error(`Échec de la conversion ${file}:`, error.message);
}
}
}
}Outils de validation
Valider l'intégrité de l'image
javascript
async function validateImage(filePath) {
try {
const metadata = await sharp(filePath).metadata();
// Vérifier les propriétés de base
if (!metadata.width || !metadata.height) {
return { valid: false, error: 'Informations de dimensions manquantes' };
}
if (metadata.width <= 0 || metadata.height <= 0) {
return { valid: false, error: 'Dimensions invalides' };
}
if (!metadata.format) {
return { valid: false, error: 'Informations de format manquantes' };
}
// Essayer de traiter l'image
await sharp(filePath).resize(1, 1).toBuffer();
return { valid: true, metadata };
} catch (error) {
return { valid: false, error: error.message };
}
}Vérifier la taille du fichier
javascript
const fs = require('fs');
function checkFileSize(filePath, maxSize = 10 * 1024 * 1024) { // 10MB
const stats = fs.statSync(filePath);
const sizeInMB = stats.size / (1024 * 1024);
return {
size: stats.size,
sizeInMB,
isValid: stats.size <= maxSize,
maxSizeInMB: maxSize / (1024 * 1024)
};
}