2

I want to generate images in different sizes from one base image. F.e. I have an 1920x1080 image and after processing I want images with sizes (768, 1024, 1600, 1920).

I know there is an loader which can accomplish that: https://github.com/herrstucki/responsive-loader

However, I have many view scripts of an "legacy" PHP application (Zend Framework 3), which are not processed by webpack (no HtmlWebpackPlugin) as it would be too complicated to get this working along with the Zend Framework.

Is there a way, to just point to the source directory (glob) of my images and convert all images there and save them (and there generated versions) to my dist folder?

I do something similar with ImageMin:

const
    path = require('path'),
    glob = require('glob'),
    manifest = require('../manifest'),
    ImageminWebpWebpackPlugin = require('imagemin-webp-webpack-plugin'),
    ImageminPlugin = require('imagemin-webpack-plugin').default,
    ImageminJpegoptim = require('imagemin-jpegoptim'),
    ImageminOptipng = require('imagemin-optipng'),
    Gifsicle = require('imagemin-gifsicle'),
    CopyWebpackPlugin = require('copy-webpack-plugin');

// const files = glob.sync(path.join(manifest.paths.src, 'public/images/**/*.jpg'));

const quality = 50;

let copyOptions = [
    {
        context: path.join(manifest.paths.src, 'public/images/'),
        from: '!(.tmb|captcha)/**/*',
        to: path.join(manifest.paths.dist, 'images/'),
    },
    {
        context: path.join(manifest.paths.src, 'public/images/'),
        from: '*',
        to: path.join(manifest.paths.dist, 'images/'),
    }
];

// plugin config which gets passed to webpack config (pushed to plugins: [...])
module.exports = [
    new CopyWebpackPlugin(copyOptions),
    new ImageminWebpWebpackPlugin({
        config: [{
            test: /\.(jpe?g|png)/,
            options: {
                quality:  quality
            }
        }],
        overrideExtension: true,
        detailedLogs: false,
        strict: true
    }),
    new ImageminPlugin({
        //disable: manifest.IS_DEVELOPMENT,
        test: /\.(jpe?g|png|gif|svg)$/i,
        cacheFolder: path.join(manifest.paths.src, 'public/.cache'),
        plugins: [
            ImageminJpegoptim({
                // if you change this, do not foget to empty the cache folder!
                max: quality
            }),
            ImageminOptipng({
                optimizationLevel: 7
            }),
            Gifsicle({
                optimizationLevel: 3
            })
        ],
    })
];

This config converts my images down to web friendly sizes (in terms of filesize!). Is there a chance to integrate the process of generating multiple image sizes (in terms of dimension!) in this config?

koseduhemak
  • 523
  • 2
  • 4
  • 19

1 Answers1

0

For time travellers looking for a solution; I used image-minimizer-webpack-plugin and sharp to generate images in different sizes from a single image

// webpack.config.ts

import CopyWebpackPlugin from "copy-webpack-plugin";
import ImageMinimizerPlugin from "image-minimizer-webpack-plugin";

const imagesToGenerate = {
  "assets/images/logo.png": {
    name: "icon",
    sizes: [24, 32, 64]
  ],
  "assets/images/preview.png": {
    name: "preview",
    sizes: [256, 512]
  ]
}

export default {
  // this does not conflict with other webpack settings
  // include the images to generate as assets passed to optimisation
  plugins: [new CopyPlugin({ patterns: Object.keys(imagesToGenerate) })],
  // optimisation step for image generation (see guide for more opts)
  optimization: {
    minimizer: [
      ...Object.entries(imagesToGenerate).map(([imgSrc, imgConfig]) => {
        const fileType = path.extname(imgSrc).substring(1);
        return new ImageMinimizerPlugin({
          generator: imgConfig.sizes.map((size) => ({
            type: "asset",
            implementation: async (original, options) => {
              const result = await ImageMinimizerPlugin.sharpGenerate(
                original,
                options,
              );
              // files already end up the the configured output path
              // this is to customise the name based on resize config
              const fileExt = path.extname(result.filename);
              result.filename = `${imgConfig.name}_${size}${fileExt}`;
              return result;
            },
            options: {
              // encode option is required so setting max quality for resize
              encodeOptions: {
                [fileType]: {
                  quality: 100,
                },
              },
              resize: {
                enabled: true,
                height: size,
                width: size,
              },
            },
          })),
        });
      }),
    ],
  },
};

code

The guide at https://github.com/webpack-contrib/image-minimizer-webpack-plugin#generate-webp-images-from-copied-assets shows alternatives to sharp for image transforms.

iamogbz
  • 99
  • 1
  • 13