6 个版本 (重大更改)

0.7.0 2021年1月25日
0.6.0 2020年4月13日
0.5.0 2020年4月7日
0.4.0 2020年3月22日
0.2.0 2019年10月29日

#345WebAssembly


2 包 中使用

MIT 许可证

23KB
443 代码行

🎨 Pigmnts

Pigmnts 是一个使用 Rust 构建、编译为 WebAssembly 的库,用于从图像创建调色板。这使得在网络上从图像中提取调色板变得非常快。它使用 K-means++ 聚类算法从图像中选择最常出现的颜色。

WebAssembly 中的示例

作为一个 JavaScript 模块

<script type="module">
  // Import the functions from CDN
  import init, { pigments } from 'https://unpkg.com/pigmnts/pigmnts.js';

  async function run() {
    /**
     * Load the wasm file.
     * Replace the URL with a different path if you want to use
     * self hosted wasm file 
     */
    await init('https://unpkg.com/pigmnts/pigmnts_bg.wasm');

    // Canvas element from which palette should be created
    const canvas = document.querySelector('canvas');

    // Call the pigments wasm function
    const palette = pigments(canvas, 5);
  }
  run();

</script>

在 Node.js 中

  1. 首先安装 npm 包
npm install pigmnts
  1. 配置您的构建过程以将 wasm 文件复制到您的构建目录。

  2. 在代码中使用它

import init, { pigments } from 'pigmnts';

async function run() {
  // Load the wasm file from path where wasm file was copied by the bundler
  await init('<path to the wasm file>');

  // Canvas element from which palette should be created
  const canvas = document.querySelector('canvas');

  // Call the pigments wasm function
  const palette = pigments(canvas, 5);
}
run();

函数

Pigmnts 在 WebAssembly 中公开以下函数

pigments(canvas: HtmlCanvasElement, k: number, mood: Mood|number, batch_size: number)

参数
  • canvas 需要处理的图像的 canvas 元素。内部,从 canvas 中获取像素数据,然后进行聚类以创建调色板。
  • k 定义从图像中收集的颜色数量。
  • mood 定义要使用的权重函数。仅支持 'dominant' 情绪,其值为 0
  • batch_size(可选)定义从图像中随机采样的像素数量。它应该大于图像中的总像素数和 k。默认情况下,处理图像中的所有像素。
返回值

返回一个对象数组,其中每个对象都是以下格式的颜色。

[
  {
    dominance: 0.565    // Dominance of color in image(From 0 to 1)
    hex: '#6DDAD0'      // 6-digit Hex color code
    rgb: {              // Equivalent RGB color
      r: 109,
      g: 218,
      b: 208
    },
    hsl: {             // Equivalent HSL color (Normalized to 0-1)
      h: 0.48333,
      s: 0.6,
      l: 0.64,
    }
  },
  // Other colors
  {
    ...
  }
]

如果在这个 crate 中使用了某个 Rust 项目,则还可以使用以下函数

颜料像素(pigments_pixels(pixels: &Vec<LAB>, k: u8, weight: fn(&LAB) -> f32, max_iter: Option<u16>) -> Vec<(LAB, f32)>

此函数可用于从使用image-rs解码的图像中收集颜色数据时。

参数
  • pixels引用的是LAB格式的颜色向量。
  • k 定义从图像中收集的颜色数量。
  • weight定义要使用的权重函数。src/weights.rs文件实现了几个权重函数。
  • max_iter定义算法执行的最大迭代次数,默认为300
返回值

返回一个包含颜色作为LAB和图像中找到的每种颜色的占比(百分比)的元组的向量。

许可

Pigmnts遵循MIT 许可协议

依赖

~8–10MB
~202K SLoC