@frostoven/libsquoosh

中文文档
0.4.8发布于 2024/04/29Apache-2.0CommonJS近 30 天下载 2609

The Node backend of the Squoosh CLI package

原始使用文档
文档目录7 节
  1. Installation
  2. Ingesting images
  3. Preprocessing and encoding images
  4. Closing the ImagePool
  5. Writing encoded images to the file system
  6. Extracting image information
  7. Auto optimizer

libSquoosh

libSquoosh is an experimental JavaScript backend used by its related CLI package. While you may use this library in your own projects, please beware that it's not considered production-ready for general use, and there are no immediate plans to make it so. If you use this package, you do so at your own risk.

libSquoosh uses a worker pool to parallelize processing images. This way you can apply the same codec to many images at once.

libSquoosh is currently not the fastest image compression tool in town and doesn't aim to be. It is, however, fast enough to compress many images sufficiently quick at once.

Please note that this is a fork of the original library, which has since been retired. This fork continues that work and has some bug fixes.

Installation

libSquoosh can be installed to your local project with the following command:

$ npm install @frostoven/libsquoosh

You can start using the libSquoosh by adding these lines to the top of your JS program:

import { ImagePool } from '@frostoven/libsquoosh';
import { cpus } from 'os';
const imagePool = new ImagePool(cpus().length);

This will create an image pool with an underlying processing pipeline that you can use to ingest and encode images. The ImagePool constructor takes one argument that defines how many parallel operations it is allowed to run at any given time. By default, this number is set to the amount of CPU cores available in the system it is running on.

Ingesting images

You can ingest a new image like so:

import fs from 'fs/promises';
const file = await fs.readFile('./path/to/image.png');
const image = imagePool.ingestImage(imagePath);

The ingestImage function can accept any ArrayBuffer whether that is from readFile() or fetch().

The returned image object is a representation of the original image, that you can now preprocess, encode, and extract information about.

Preprocessing and encoding images

When an image has been ingested, you can start preprocessing it and encoding it to other formats. This example will resize the image and then encode it to a .jpg and .jxl image:

await image.decoded; //Wait until the image is decoded before running preprocessors.

const preprocessOptions = {
  //When both width and height are specified, the image resized to specified size.
  resize: {
    enabled: true,
    width: 100,
    height: 50,
  },
  /*
  //When either width or height is specified, the image resized to specified size keeping aspect ratio.
  resize: {
    enabled: true,
    width: 100,
  }
  */
};
await image.preprocess(preprocessOptions);

const encodeOptions = {
  mozjpeg: {}, //an empty object means 'use default settings'
  jxl: {
    quality: 90,
  },
};
await image.encode(encodeOptions);

The default values for each option can be found in the codecs.ts file under defaultEncoderOptions. Every unspecified value will use the default value specified there. Better documentation is needed here.

You can run your own code inbetween the different steps, if, for example, you want to change how much the image should be resized based on its original height. (See Extracting image information to learn how to get the image dimensions).

Closing the ImagePool

When you have encoded everything you need, it is recommended to close the processing pipeline in the ImagePool. This will not delete the images you have already encoded, but it will prevent you from ingesting and encoding new images.

Close the ImagePool pipeline with this line:

await imagePool.close();

Writing encoded images to the file system

When you have encoded an image, you normally want to write it to a file.

This example takes an image that has been encoded as a jpg and writes it to a file:

const rawEncodedImage = (await image.encodedWith.mozjpeg).binary;

fs.writeFile('/path/to/new/image.jpg', rawEncodedImage);

This example iterates through all encoded versions of the image and writes them to a specific path:

const newImagePath = '/path/to/image.'; //extension is added automatically

for (const encodedImage of Object.values(image.encodedWith)) {
  fs.writeFile(
    newImagePath + (await encodedImage).extension,
    (await encodedImage).binary,
  );
}

Extracting image information

Information about a decoded image is available at Image.decoded. It looks something like this:

console.log(await image.decoded);
// Returns:
{
 bitmap: {
    data: Uint8ClampedArray(47736584) [
      225, 228, 237, 255, 225, 228, 237, 255, 225, 228, 237, 255,
      225, 228, 237, 255, 225, 228, 237, 255, 225, 228, 237, 255,
      225, 228, 237, 255,
      ... //the entire raw image
    ],
    width: 4606,  //pixels
    height: 2591  //pixels
  },
  size: 2467795  //bytes
}

Information about an encoded image can be found at Image.encodedWith[encoderName]. It looks something like this:

console.log(await image.encodedWith.jxl);
// Returns:
{
  optionsUsed: {
    quality: 75,
    baseline: false,
    arithmetic: false,
    progressive: true,
    ... //all the possible options for this encoder
  },
  binary: Uint8Array(1266975) [
      1,   0,   0,   1,   0,  1,  0,  0, 255, 219,  0, 132,
    113, 119, 156, 156, 209,  1,  8,  8,   8,   8,  9,   8,
      9,  10,  10,   9,
    ... //the entire raw encoded image
  ],
  extension: 'jxl',
  size: 1266975  //bytes
}

Auto optimizer

libSquoosh has an experimental auto optimizer that compresses an image as much as possible, trying to hit a specific Butteraugli target value. The higher the Butteraugli target value, the more artifacts can be introduced.

You can make use of the auto optimizer by using “auto” as the config object.

const encodeOptions: {
  mozjpeg: 'auto',
}

版本与发布记录

@frostoven/libsquoosh 共发布 8 个版本,首次发布于 2023/05/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.4.8latest2024/04/292 年前
0.4.72024/01/092 年前
0.4.62023/09/273 年前
0.4.52023/09/263 年前
0.4.42023/09/263 年前
0.4.32023/09/263 年前

关于 @frostoven/libsquoosh 的常见问题

@frostoven/libsquoosh 是什么?

The Node backend of the Squoosh CLI package

如何安装 @frostoven/libsquoosh?

在项目目录运行 npm install @frostoven/libsquoosh,或使用 pnpm add / yarn add / bun add。

@frostoven/libsquoosh 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/frostoven__libsquoosh 是否存在。

@frostoven/libsquoosh 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@frostoven/libsquoosh 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@frostoven/libsquoosh 可以商用吗?

@frostoven/libsquoosh 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@frostoven/libsquoosh 的下载量有多少?

根据 npm 官方下载统计,@frostoven/libsquoosh 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,609 次,日均约 87 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@frostoven/libsquoosh 还在维护吗?

最新版本 0.4.8 发布于 2024/04/29(2 年前);至今共发布 8 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/05/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。