当前位置: 首页 > 工具软件 > pngquant > 使用案例 >

在node中使用 PngQuant

越雨泽
2023-12-01

在node中使用 PngQuant

1. 依赖准备

2. 使用方法

官方示例:

var PngQuant = require('pngquant'),
  myPngQuanter = new PngQuant([192, '--quality', '60-80', '--nofs', '-']);

sourceStream.pipe(myPngQuanter).pipe(destinationStream);

官方示例非常简约,很多人一看就直接晕了,特别是都没接触过 MemoryStream 的人,我也是在官方的github仓库中看到了相关内容才知道需要用 MemoryStream 的,所以上面依赖我就推荐安装两个了,若果有别的 MemoryStream也可以用别的。下面展示我的demo:

const fs = require('fs');
const path = require('path');
const PngQuant = require('pngquant');
const MemoryStream = require('memory-stream');

let sourceImg = path.join(__dirname, '原图 与当前js文件所在目录的相对路径');
let compressedImg = path.join(__dirname, '压缩后图 与当前js文件所在目录的相对路径');

const sourceStream = fs.createReadStream(sourceImg);
const destinationStream = new MemoryStream();

const myPngQuanter = new PngQuant([192, '--quality', '60-80', '--nofs', '-']);

sourceStream.pipe(myPngQuanter).pipe(destinationStream);

// 完成压缩的图片转为buffer然后保存为图片
destinationStream.on('finish', function () {
  // 把buffer写入到图片文件
  fs.writeFile(compressedImg, destinationStream.toBuffer(), function (err) {
    if (err) {
      console.log(err);
    }
  });
});

压缩后的png图片效果很明显,有80%多的压缩率,而且图片肉眼看基本不失真,压缩算法很不错。

3. 命令分析

node 中使用 pngquant 时,传入的一个数组参数是一个 options ,其实相当于使用命令行时输入的命令参数。
示例中使用的参数,转换成命令行应该是:

pngquant --quality=60-80 --nofs=-

在命令行使用时,语法是这样的:

# 1
pngquant [options] [ncolors] -- pngfile [pngfile ...]
# 2
pngquant [options] [ncolors] - >stdout <stdin
usage:  pngquant [options] [ncolors] [pngfile [pngfile ...]]

options:
  --force           overwrite existing output files (synonym: -f)
  --nofs            disable Floyd-Steinberg dithering
  --ext new.png     set custom suffix/extension for output filename
  --speed N         speed/quality trade-off. 1=slow, 3=default, 10=fast & rough
  --quality min-max don't save below min, use less colors below max (0-100)
  --verbose         print status messages (synonym: -v)
  --iebug           increase opacity to work around Internet Explorer 6 bug
  --transbug        transparent color will be placed at the end of the palette

Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette
PNGs using Floyd-Steinberg diffusion dithering (unless disabled).
The output filename is the same as the input name except that
it ends in "-fs8.png", "-or8.png" or your custom extension (unless the
input is stdin, in which case the quantized image will go to stdout).
The default behavior if the output file exists is to skip the conversion;
use --force to overwrite.

所以想要增加配置,直接在New QngQuant 中增加即可

 类似资料: