83 lines
2.7 KiB
JavaScript
83 lines
2.7 KiB
JavaScript
const sharp = require('sharp');
|
|
const axios = require('axios');
|
|
const fs = require('fs').promises;
|
|
const path = require('path');
|
|
|
|
async function downloadImage(url, destination) {
|
|
try {
|
|
const response = await axios({
|
|
url,
|
|
method: 'GET',
|
|
responseType: 'arraybuffer',
|
|
});
|
|
await fs.writeFile(destination, response.data);
|
|
} catch (error) {
|
|
console.error(`Erreur lors du téléchargement de l'image ${url}:`, error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function generateImage(imageUrls, outputPath) {
|
|
const tempDir = path.join(__dirname, 'temp');
|
|
await fs.mkdir(tempDir, {recursive: true});
|
|
|
|
const images = [];
|
|
|
|
for (const imageUrl of imageUrls) {
|
|
try {
|
|
const tempPath = path.join(tempDir, `${Date.now()}-${Math.random().toString(36).substr(2, 9)}.jpg`);
|
|
await downloadImage(imageUrl, tempPath);
|
|
images.push(sharp(tempPath));
|
|
} catch (error) {
|
|
console.error(`Impossible de télécharger l'image ${imageUrl}. Elle sera ignorée.`);
|
|
}
|
|
}
|
|
|
|
if (images.length === 0) {
|
|
throw new Error("Aucune image n'a pu être téléchargée.");
|
|
}
|
|
|
|
const firstImage = await images[0].metadata();
|
|
const width = firstImage.width;
|
|
const height = firstImage.height;
|
|
|
|
const composite = sharp({
|
|
create: {
|
|
width: width * images.length,
|
|
height,
|
|
channels: 4,
|
|
background: {r: 255, g: 255, b: 255, alpha: 1}
|
|
}
|
|
});
|
|
|
|
const compositeOperations = await Promise.all(images.map(async (image, index) => ({
|
|
input: await image.toBuffer(),
|
|
top: 0,
|
|
left: width * index
|
|
})));
|
|
|
|
await composite.composite(compositeOperations).toFile(outputPath);
|
|
|
|
// Supprimer les images temporaires
|
|
for (const image of images) {
|
|
image.destroy();
|
|
}
|
|
|
|
const files = await fs.readdir(tempDir);
|
|
for (const file of files) {
|
|
await fs.unlink(path.join(tempDir, file));
|
|
}
|
|
}
|
|
|
|
// Exemple d'utilisation
|
|
const imageUrls = [
|
|
'https://mastodon.cipherbliss.com/system/cache/accounts/avatars/000/012/606/original/37deaa900b17861d.png',
|
|
'https://mastodon.cipherbliss.com/system/cache/accounts/avatars/000/012/606/original/37deaa900b17861d.png',
|
|
'https://mastodon.cipherbliss.com/system/cache/accounts/avatars/000/012/606/original/37deaa900b17861d.png',
|
|
];
|
|
|
|
const outputPath = path.join(__dirname, 'documents', 'generated_pictures', 'combined_images.jpg');
|
|
|
|
generateImage(imageUrls, outputPath)
|
|
.then(() => console.log('Image générée avec succès!'))
|
|
.catch((err) => console.error('Erreur lors de la génération de l\'image:', err)); |