How to use the imagemin.buffer function in imagemin

To help you get started, we’ve selected a few imagemin examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github itgalaxy / imagemin-power-cli / cli.js View on Github external
try {
            // eslint-disable-next-line global-require, import/no-dynamic-require
            config = require(path.resolve(dataSource));
        } catch (error) {
            console.error(`Cannot require "config"\n${error}`); // eslint-disable-line no-console
            process.exit(1); // eslint-disable-line no-process-exit
        }

        opts.plugin = config.plugins;
    } else {
        opts.plugin = requirePlugins(arrify(opts.plugin));
    }

    if (Buffer.isBuffer(input)) {
        return imagemin
            .buffer(input, {
                plugins: opts.plugin
            })
            .then(buf => process.stdout.write(buf));
    }

    let spinner = null;

    if (opts.verbose || opts.silent) {
        spinner = ora();

        if (opts.verbose) {
            spinner.text = "Starting minifying images...";
            spinner.start();
        }
    }
github tcoopman / image-webpack-loader / index.js View on Github external
// default optimizers
    if(options.gifsicle.enabled !== false)
      plugins.push(require('imagemin-gifsicle')(options.gifsicle));
    if(options.mozjpeg.enabled !== false)
      plugins.push(require('imagemin-mozjpeg')(options.mozjpeg));
    if(options.svgo.enabled !== false)
      plugins.push(require('imagemin-svgo')(options.svgo));
    if(options.pngquant.enabled !== false)
      plugins.push(require('imagemin-pngquant')(options.pngquant));
    if(options.optipng.enabled !== false)
      plugins.push(require('imagemin-optipng')(options.optipng));
    // optional optimizers
    if(options.webp)
      plugins.push(require('imagemin-webp')(options.webp));

    imagemin
      .buffer(content, {
        plugins
      })
      .then(data => {
        callback(null, data);
      })
      .catch(err => {
        callback(err);
      });
  }
};
github mamboer / hexo-filter-cleanup / lib / img.js View on Github external
}

                if (options.webp && ext === '.webp') {
                    imageminOption.plugins.push(webpmin({quality: options.webpQuality}));
                }

                // Add additional plugins.
                if (options.pngquant && ext === '.png') { // Lossy compression.
                    imageminOption.plugins.push(pngquant());
                }

                if (options.jpegrecompress && ['.jpg', '.jpeg'].indexOf(ext) !== -1) {
                    imageminOption.plugins.push(jpegrecompress({quality: options.jpegrecompressQuality}));
                }

                return imagemin.buffer(buffer, imageminOption)
                    .then(function (newBuffer) {
                        let length = buffer.length;
                        if (newBuffer && length > newBuffer.length) {
                            let saved = ((length - newBuffer.length) / length * 100).toFixed(2);
                            log.log('%s(IMG): %s [ %s saved]', pkg.name, path, saved + '%');
                            route.set(path, newBuffer); // Update the route.
                        }
                    });
            });
    });
github vanniktech / Emoji / generator / index.js View on Github external
emojiByStrip[it.sheet_x] = new Array(it);
        }
    });

    const src = `node_modules/emoji-datasource-${target.dataSource}/img/${target.dataSource}/sheets/64.png`;
    const sheet = await Jimp.read(src);
    const strips = sheet.bitmap.width / 66 - 1;
    for (let i = 0; i < strips; i++) {
        const maxY = emojiByStrip[i].map(it => it.sheet_y).reduce((a, b) => Math.max(a, b), 0);
        const height = (maxY + 1) * 66;
        const strip = await new Jimp(66, height);
        await strip.blit(sheet, 0, 0, i * 66, 0, 66, height);
        const dest = `../emoji-${target.package}/src/main/res/drawable-nodpi/emoji_${target.package}_sheet_${i}.png`;
        if (shouldOptimize) {
            const buffer = await strip.getBufferAsync('image/png');
            const optimizedStrip = await imagemin.buffer(buffer, {
                plugins: [
                    imageminPngquant(),
                    imageminZopfli()
                ]
            });
            await fs.writeFile(dest, optimizedStrip);
        } else {
            await strip.writeAsync(dest);
        }
    }

    for (const [category] of map) {
        await fs.copy(`img/${category.toLowerCase()}.png`,
            `../emoji-${target.package}/src/main/res/drawable-nodpi/emoji_${target.package}_category_${category.toLowerCase()}.png`);
    }
}
github motivast / motimize / src / services / optimize.js View on Github external
optimize(buffer, mime_type, quality) {
    logger.info("Optimization.");
    logger.info(
      'Optimization: Optimize image with quality "' + quality + '".'
    );

    logger.info("Optimization: Start buffer optimization.");
    return imagemin.buffer(buffer, {
      plugins: getPlugins(mime_type, quality)
    });
  }
}
github kavu / webp-loader / index.js View on Github external
module.exports = function (content) {
  this.cacheable && this.cacheable();

  var query = loaderUtils.getOptions(this) || {};
  var configKey = query.config || 'webpLoader';
  var options = this.options && this.options[configKey] || {};
  var config = Object.assign({}, options, query);

  var callback = this.async();

  if (this.debug === true && config.bypassOnDebug === true) {
    return callback(null, content);
  } else {
    imagemin
      .buffer(content,{
        plugins: [imageminWebp(config)]
      })
      .then(function(data){
        callback(null, data);
      })
      .catch(function(err){
        callback(err);
      });
  }
};
github apostrophecms / uploadfs / lib / image / imagemin.js View on Github external
.then(function(buffer) {
            return imagemin.buffer(buffer, {
              plugins: [ imageminSvgo(options.svgo || {}) ]
            })
          })
          .then(function(buffer) {
github hex-ci / resource-uploader / lib / imagemin.js View on Github external
cb(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
      return;
    }

    if (!validExts.includes(path.extname(file.path).toLowerCase())) {
      if (options.verbose) {
        log(`${PLUGIN_NAME}: Skipping unsupported image ${chalk.blue(file.relative)}`);
      }

      cb(null, file);
      return;
    }

    const use = plugins || getDefaultPlugins();

    imagemin.buffer(file.contents, {use})
      .then(data => {
        const originalSize = file.contents.length;
        const optimizedSize = data.length;
        const saved = originalSize - optimizedSize;
        const percent = originalSize > 0 ? (saved / originalSize) * 100 : 0;
        const savedMsg = `saved ${prettyBytes(saved)} - ${percent.toFixed(1).replace(/\.0$/, '')}%`;
        const msg = saved > 0 ? savedMsg : 'already optimized';

        if (saved > 0) {
          totalBytes += originalSize;
          totalSavedBytes += saved;
          totalFiles++;
        }

        if (options.verbose) {
          log(`${PLUGIN_NAME}:`, chalk.green('✔ ') + file.relative + chalk.gray(` (${msg})`));
github gmetais / YellowLabTools / lib / tools / redownload / imageOptimizer.js View on Github external
var engine;
        if (type === 'jpeg' && !lossy) {
            engine = imageminJpegtran({progressive: true});
        } else if (type === 'jpeg' && lossy) {
            engine = imageminJpegoptim({progressive: true, max: MAX_JPEG_QUALITY});
        } else if (type === 'png' && !lossy) {
            engine = imageminOptipng({optimizationLevel: OPTIPNG_COMPRESSION_LEVEL});
        } else if (type === 'svg' && !lossy) {
            engine = imageminSvgo({ plugins: [ { removeUselessDefs: false } ] });
        } else {
            deferred.reject('No optimization engine found for imagemin');
        }


        imagemin.buffer(imageBody, {use: engine})

        .then(function(file) {
            var endTime = Date.now();
            debug('Optimization for %s took %d ms', type, endTime - startTime);
            deferred.resolve(file);
        })

        .catch(function(err) {
            debug('Optimisation failed:');
            debug(err);
            deferred.resolve();
        });

        return deferred.promise;
    }

imagemin

Minify images seamlessly

MIT
Latest version published 6 months ago

Package Health Score

79 / 100
Full package analysis