我试图从一个输入文件夹中的图像与6位,优化他们相应地和输出他们作为WebP文件都具有不同的宽度被用作srcset图像内我的网站与名称对流为每个文件从1和升序,直到与子文件夹的图像列表完成。代码我已经得到了帮助写是
`
const fs = require('fs');
const sharp = require('sharp');
// Define the input directory
const inputDirectory = './input';
// Create an array to define categories and their settings
const categories = [
{ name: 'Important', minWidth: 1080, maxWidth: 2000, quality: 90 },
{ name: 'Gallery', minWidth: 800, maxWidth: 2000, quality: 80 },
{ name: 'Digitals', minWidth: 800, maxWidth: 2000, quality: 80 },
{ name: 'Contact', minWidth: 800, maxWidth: 1600, quality: 60 },
{ name: 'Misc', minWidth: 500, maxWidth: 1080, quality: 30 },
{ name: 'Loader', minWidth: 500, maxWidth: 1600, quality: 30 },
];
// Function to process images in a category
async function processCategory(category) {
const inputFolder = `${inputDirectory}/${category.name}`;
const outputFolder = `./output/${category.name}`;
// Create the output folder if it doesn't exist
if (!fs.existsSync(outputFolder)) {
fs.mkdirSync(outputFolder, { recursive: true });
}
const files = fs.readdirSync(inputFolder);
let imageNumber = 1;
for (const file of files) {
const inputPath = `${inputFolder}/${file}`;
const image = sharp(inputPath);
// Get image metadata
const metadata = await image.metadata();
// Check if the image width is within the specified range
if (metadata.width >= category.minWidth && metadata.width <= category.maxWidth) {
// Resize and optimize the image
await image
.webp({ quality: category.quality })
.toFile(`${outputFolder}/${imageNumber}-${metadata.width}.webp`);
imageNumber++;
}
}
}
// Main function to process all categories
async function processAllCategories() {
for (const category of categories) {
await processCategory(category);
}
}
// Start the image processing
processAllCategories()
.then(() => {
console.log('Image processing completed.');
})
.catch((error) => {
console.error('Error processing images:', error);
});`
字符串
然而,它只需要一个图像,并将其转换为900 p,就是这样!有人知道tf是怎么回事吗?谢谢你的时间,感谢你阅读这一点,卢克:)
1条答案
按热度按时间wf82jlnq1#
当你调用sharp(inputPath)时,你应该尝试输入一个await:
字符串