Référence API
Sharp fournit une API riche pour traiter les images. Cette page fournit une référence détaillée de toutes les méthodes disponibles.
Constructeur
sharp(input, options?)
Crée une nouvelle instance Sharp.
import sharp from 'sharp';
// Créer depuis un fichier
const image = sharp('input.jpg');
// Créer depuis un Buffer
const image = sharp(buffer);
// Créer depuis un Stream
const image = sharp(stream);
// Créer une image vide
const image = sharp({
create: {
width: 300,
height: 200,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 1 }
}
});Métadonnées d'entrée
metadata()
Obtenir les informations de métadonnées de l'image.
const metadata = await sharp('input.jpg').metadata();
console.log(metadata);
// {
// format: 'jpeg',
// width: 1920,
// height: 1080,
// space: 'srgb',
// channels: 3,
// depth: 'uchar',
// density: 72,
// hasProfile: false,
// hasAlpha: false
// }stats()
Obtenir les statistiques de l'image.
const stats = await sharp('input.jpg').stats();
console.log(stats);
// {
// isOpaque: true,
// dominant: { r: 128, g: 128, b: 128 }
// }Options de sortie
toFile(filename, callback?)
Enregistrer l'image traitée dans un fichier.
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');toBuffer(options?, callback?)
Sortir l'image traitée sous forme de Buffer.
const buffer = await sharp('input.jpg')
.resize(300, 200)
.jpeg()
.toBuffer();toFormat(format, options?)
Définir le format de sortie.
// JPEG
await sharp('input.png')
.jpeg({ quality: 80, progressive: true })
.toFile('output.jpg');
// PNG
await sharp('input.jpg')
.png({ compressionLevel: 9, adaptiveFiltering: true })
.toFile('output.png');
// WebP
await sharp('input.jpg')
.webp({ quality: 80, effort: 6 })
.toFile('output.webp');
// AVIF
await sharp('input.jpg')
.avif({ quality: 80, effort: 4 })
.toFile('output.avif');
// TIFF
await sharp('input.jpg')
.tiff({ quality: 80, compression: 'lzw' })
.toFile('output.tiff');Ajustement d'image
resize(width?, height?, options?)
Redimensionner l'image.
// Redimensionnement de base
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
// Conserver le ratio d'aspect
await sharp('input.jpg')
.resize(300, null)
.toFile('output.jpg');
// Utiliser le mode d'adaptation
await sharp('input.jpg')
.resize(300, 200, {
fit: 'cover', // Recadrer pour s'adapter
position: 'center', // Recadrage centré
background: { r: 255, g: 255, b: 255, alpha: 1 }
})
.toFile('output.jpg');
// Utiliser un noyau
await sharp('input.jpg')
.resize(300, 200, {
kernel: sharp.kernel.lanczos3
})
.toFile('output.jpg');extract(region)
Recadrer une zone de l'image.
await sharp('input.jpg')
.extract({ left: 100, top: 100, width: 200, height: 200 })
.toFile('cropped.jpg');trim(threshold?)
Recadrage automatique des bords transparents ou blancs.
await sharp('input.png')
.trim()
.toFile('trimmed.png');Opérations d'image
rotate(angle, options?)
Faire pivoter l'image.
// Rotation de 90 degrés
await sharp('input.jpg')
.rotate(90)
.toFile('rotated.jpg');
// Rotation avec remplissage de fond
await sharp('input.jpg')
.rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
.toFile('rotated.jpg');flip(flip?)
Retourner l'image verticalement.
await sharp('input.jpg')
.flip()
.toFile('flipped.jpg');flop(flop?)
Retourner l'image horizontalement.
await sharp('input.jpg')
.flop()
.toFile('flopped.jpg');affine(matrix, options?)
Appliquer une transformation affine.
await sharp('input.jpg')
.affine([[1, 0.3], [0, 1]], { background: { r: 255, g: 255, b: 255, alpha: 1 } })
.toFile('transformed.jpg');Effets de filtre
blur(sigma?)
Appliquer un flou gaussien.
await sharp('input.jpg')
.blur(5)
.toFile('blurred.jpg');sharpen(sigma?, flat?, jagged?)
Appliquer un filtre de netteté.
await sharp('input.jpg')
.sharpen()
.toFile('sharpened.jpg');
// Paramètres de netteté personnalisés
await sharp('input.jpg')
.sharpen(1, 1, 2)
.toFile('sharpened.jpg');median(size?)
Appliquer un filtre médian.
await sharp('input.jpg')
.median(3)
.toFile('median.jpg');flatten(options?)
Fusionner le canal transparent.
await sharp('input.png')
.flatten({ background: { r: 255, g: 255, b: 255 } })
.toFile('flattened.jpg');Opérations de couleur
grayscale(grayscale?)
Convertir en image en niveaux de gris.
await sharp('input.jpg')
.grayscale()
.toFile('grayscale.jpg');negate(negate?)
Effet négatif.
await sharp('input.jpg')
.negate()
.toFile('negated.jpg');modulate(options?)
Ajuster la luminosité, la saturation et la teinte.
await sharp('input.jpg')
.modulate({
brightness: 1.2, // Luminosité
saturation: 0.8, // Saturation
hue: 90 // Teinte
})
.toFile('modulated.jpg');tint(rgb)
Appliquer une teinte.
await sharp('input.jpg')
.tint({ r: 255, g: 0, b: 0 })
.toFile('tinted.jpg');removeAlpha()
Supprimer le canal alpha.
await sharp('input.png')
.removeAlpha()
.toFile('no-alpha.jpg');ensureAlpha()
S'assurer qu'il y a un canal alpha.
await sharp('input.jpg')
.ensureAlpha()
.toFile('with-alpha.png');Opérations de canaux
bandbool(boolean)
Appliquer une opération booléenne aux canaux.
await sharp('input.jpg')
.bandbool('and')
.toFile('bandbool.jpg');joinChannel(channels)
Fusionner les canaux.
await sharp('input.jpg')
.joinChannel(['red.jpg', 'green.jpg', 'blue.jpg'])
.toFile('joined.jpg');extractChannel(channel)
Extraire un canal unique.
await sharp('input.jpg')
.extractChannel('red')
.toFile('red-channel.jpg');Propriétés globales
sharp.versions
Obtenir les informations de version.
console.log(sharp.versions);
// {
// sharp: '0.32.0',
// vips: '8.14.0'
// }sharp.format
Obtenir les formats supportés.
console.log(sharp.format);
// {
// jpeg: { id: 'jpeg', ... },
// png: { id: 'png', ... },
// webp: { id: 'webp', ... },
// ...
// }sharp.kernel
Obtenir les noyaux disponibles.
console.log(sharp.kernel);
// {
// nearest: 'nearest',
// cubic: 'cubic',
// mitchell: 'mitchell',
// lanczos2: 'lanczos2',
// lanczos3: 'lanczos3'
// }Gestion des erreurs
try {
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
} catch (error) {
console.error('Échec du traitement d'image:', error);
}Optimisation des performances
Traitement en flux
const pipeline = sharp()
.resize(300, 200)
.jpeg({ quality: 80 });
fs.createReadStream('large-input.jpg')
.pipe(pipeline)
.pipe(fs.createWriteStream('output.jpg'));Traitement concurrent
const promises = images.map(image =>
sharp(image)
.resize(300, 200)
.jpeg()
.toBuffer()
);
const results = await Promise.all(promises);Exemple complet
import sharp from 'sharp';
async function processImage() {
try {
// Obtenir les métadonnées
const metadata = await sharp('input.jpg').metadata();
console.log('Dimensions de l'image originale:', metadata.width, 'x', metadata.height);
// Créer plusieurs versions
const promises = [
// Miniature
sharp('input.jpg')
.resize(150, 150, { fit: 'cover' })
.jpeg({ quality: 90 })
.toFile('thumbnail.jpg'),
// Taille moyenne
sharp('input.jpg')
.resize(800, 600, { fit: 'inside' })
.webp({ quality: 80 })
.toFile('medium.webp'),
// Grande taille
sharp('input.jpg')
.resize(1920, 1080, { fit: 'inside' })
.jpeg({ quality: 85, progressive: true })
.toFile('large.jpg'),
// Version en niveaux de gris
sharp('input.jpg')
.grayscale()
.jpeg({ quality: 80 })
.toFile('grayscale.jpg')
];
await Promise.all(promises);
console.log('Tous les traitements d'image sont terminés !');
} catch (error) {
console.error('Échec du traitement:', error);
}
}
processImage();Prochaines étapes
- Consulter la page d'exemples pour en savoir plus sur l'utilisation
- Découvrir les techniques d'optimisation des performances
- Consulter le journal des modifications pour connaître les dernières fonctionnalités