nicolashmln / strapi-plugin-responsive-image

Custom responsive image formats for https://strapi.io
154 stars 28 forks source link

webp == avif #22

Closed ohbob closed 1 year ago

ohbob commented 1 year ago

Avif format isnt being processed correctly.

Add same dimensions on avif and webp and you will see the output is identical.

Let me share what im using now, maybe that will help you out.

const fs = require('fs');
const sharp = require('sharp');
const path = require('path');

const staticFolder = './public/uploads/';
const optimizedFolder = 'optim';
const formats = ['webp', 'avif'] //,'jpg'];

const sizes = {
    mini: 200,
    small: 550,
    medium: 720,
    large: 920,
    xxl: 1920,
}

if (!fs.existsSync(staticFolder)) fs.mkdirSync(staticFolder);
if (!fs.existsSync(`${staticFolder}/${optimizedFolder}`)) fs.mkdirSync(`${staticFolder}/${optimizedFolder}`);

fs.readdir(staticFolder, async (err, files) => {
    if (err) {
        console.error(err);
        return;
    }

    const images = files.filter(file => file.match(/\.(jpeg|jpg|png)$/));

    const tasks = images.map(image => {
        const imagePath = `${staticFolder}/${image}`;
        const fileName = path.parse(image).name;

        return Promise.all(
            formats.map(format =>
                Promise.all(
                    Object.keys(sizes).map(name => {
                        const currentFile = `${staticFolder}/${optimizedFolder}/${name}_${fileName}.${format}`;
                        if (!fs.existsSync(currentFile)) {
                            const width = sizes[name];
                            return sharp(imagePath)
                                .resize({ width })
                                .toFormat(format)
                                .toFile(currentFile)
                                .then(() => console.log(`Optimized ${name}_${fileName}.${format}`))
                                .catch(error => console.error(error));
                        }
                    })
                )
            )
        );
    });

    async () => {
        // Run all the tasks concurrently
        await Promise.all(tasks);
    }
});
nicolashmln commented 1 year ago

Thanks, will be fixed on next release