# autohue.js：实现图片与背景的无缝融合
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/13.%20H5%E9%80%9A%E7%94%A8%E6%8A%80%E6%9C%AF/01.%20autohue.js%E5%9B%BE%E7%89%87%E8%83%8C%E6%99%AF%E8%9E%8D%E5%90%88

本文介绍了autohue.js，一个用于提取图片主题色和边缘颜色，使图片与背景融合的JavaScript库，并详细描述了其实现原理和使用方法。


# autohue.js：实现图片与背景的无缝融合

## 需求分析

在网站设计中，经常会遇到需要将图片融入背景的情况。例如，考虑以下场景：

![网站 Banner 示例](https://cdn.widiazine.com/obsidian/86817f140e714ea4bc5d96904ab086d4.webp)

一个常见的网站 Banner 容器，尺寸为 1910x560 像素。期望背景图能够完美填充整个宽度。然而，原始图片的尺寸可能并不完全匹配，例如：

![原始图片尺寸](https://cdn.widiazine.com/obsidian/61b574aff374431ea75ddfe89318dc78.webp)

此图片的宽度仅为 1440 像素。如果 `background-size` 属性设置为 `contain`（等比例缩放），则图片两侧的留白通常需要通过背景色来填充。

**核心问题：** 对于轮播 Banner 而言，如果需要更换不同主题色的图片，为每张图片预先设定背景色显然是不可行的。

**解决方案：** 需要一种能够自动从图片中提取主色调的方案。幸运的是，JavaScript 社区已经提供了多种开源库来实现这一目标.

## 现有方案评估

目前，市面上存在一些 JavaScript 库，可以用于提取图片颜色：

- **color-thief:** 一款基于 JavaScript 和 Canvas 的工具，能够从图像中提取主要颜色或代表性的调色板。
- **vibrant.js:**  该插件是 Android 支持库中 Palette 类的 JavaScript 版本，可以从图像中提取突出的颜色。
- **rgbaster.js:** 一段小型脚本，可以获取图片的主色、次色等信息，方便实现一些 Web 交互效果。

经过初步评估，选择了轻量级的 `rgbaster.js` 进行测试。然而，在处理渐变色图片时，该库返回了大量的色值（超过七万个）。虽然它能够准确提取出面积最大的颜色值，但该颜色并非图片边缘的颜色，因此无法实现与背景的完美融合。

上述库主要侧重于颜色提取，而忽略了实际应用场景的需求。虽然它们在图片颜色分析方面表现出色，但在很多实际应用中并不适用。

另一篇文章对比了这三款插件在图片容器背景色应用上的效果，`rgbaster.js` 表现相对较好，但它仍然无法胜任颜色复杂度高或存在渐变的图片。

## 设计思路

针对现有方案的不足，决定开发一款新的工具。

期望实现以下目标：

1. 提取图片的主题色（面积占比最大）。
2. 提取次主题色（面积占比第二大）。
3. 提取合适的背景色（即图片边缘颜色，对于渐变图片，需要提取边缘颜色来设置背景色）。

通过上述目标，可以基本覆盖大部分需求。主题色和次主题色可用于生成主题标签或主题背景，而背景色则可以使留白的图片容器实现无缝融合。

## 实现方案

### 核心思路

为了避免现有插件的缺陷，特别是对渐变色图片的颜色提取问题，需要采取以下策略：

- 对渐变色进行处理，避免提取出过多的颜色值，提升性能和实用性。
- 考虑到渐变色在渐变路径上每一点的颜色都可能不同，需要设定一个阈值，将相近的颜色归类，并计算出平均颜色，避免主题色过于精确而缺乏代表性。

在背景色处理方面，需要根据具体情况进行分析。如果仅仅是为了实现页面的协调，可以直接使用主题色进行渐变过渡或添加蒙层，例如：

![主题色渐变过渡示例](https://cdn.widiazine.com/obsidian/7d0cc6cfd1684e9b8618bd46524a9dff.webp)

然而，如果需要实现背景与图片的无缝衔接，则需要单独提取边缘颜色。

此外，为了避免高分辨率图片在像素遍历时消耗过多的性能，需要降低采样率。虽然这可能会导致一定的精度损失，但通过调整到一个合适的采样率，可以保证基本可用性。

### JavaScript 代码实现

以下将详细描述 `autohue.js` 的实现过程。由于个人对色彩科学的理解有限，如有不足或错误之处，欢迎指正。

首先，定义入口主函数，并考虑以下参数：

```typescript
export default async function colorPicker(imageSource: HTMLImageElement | string, options?: autoColorPickerOptions)
type thresholdObj = { primary?: number; left?: number; right?: number; top?: number; bottom?: number }
interface autoColorPickerOptions {
  /**
   * 降采样后的最大尺寸（默认 100px）
   * 降采样后的图片尺寸不会超过该值，可根据需求调整
   * 降采样后的图片尺寸越小，处理速度越快，但可能会影响颜色提取的准确性
   **/
  maxSize?: number
  /**
   * Lab 距离阈值（默认 10）
   * 低于此值的颜色归为同一簇，建议 8~12
   * 值越大，颜色越容易被合并，提取的颜色越少
   * 值越小，颜色越容易被区分，提取的颜色越多
   **/
  threshold?: number | thresholdObj
}
```

> [!NOTE] Lab 色彩空间
> `CIE L*a*b*` 是 `CIE XYZ` 色彩模式的改进型，L 代表明亮度，a 代表绿色到红色，b 代表蓝色到黄色。`CIE L*a*b*` 色彩更适合人眼感知，具有感知均匀性 [^1]。

接下来，实现 `loadImage` 函数，使用 Canvas 异步加载图片：

```typescript
function loadImage(imageSource: HTMLImageElement | string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    let img: HTMLImageElement
    if (typeof imageSource === 'string') {
      img = new Image()
      img.crossOrigin = 'Anonymous'
      img.src = imageSource
    } else {
      img = imageSource
    }
    if (img.complete) {
      resolve(img)
    } else {
      img.onload = () => resolve(img)
      img.onerror = (err) => reject(err)
    }
  })
}
```

通过以上代码，可以获取到图片对象。

为了处理过大的图片，需要进行降采样处理：

```typescript
// 利用 Canvas 对图片进行降采样，返回 ImageData 对象
function getImageDataFromImage(img: HTMLImageElement, maxSize: number = 100): ImageData {
  const canvas = document.createElement('canvas')
  let width = img.naturalWidth
  let height = img.naturalHeight
  if (width > maxSize || height > maxSize) {
    const scale = Math.min(maxSize / width, maxSize / height)
    width = Math.floor(width * scale)
    height = Math.floor(height * scale)
  }
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext('2d')
  if (!ctx) {
    throw new Error('无法获取 Canvas 上下文')
  }
  ctx.drawImage(img, 0, 0, width, height)
  return ctx.getImageData(0, 0, width, height)
}
```

> [!NOTE] 降采样
> 降采样（Downsampling）是指在图像处理中，通过减少数据的采样率或分辨率来降低数据量的过程。简单来说，就是在保持原始信息大致特征的情况下，减少数据的复杂度和存储需求。此处将图片强制压缩为 100x100 以内，这也是 Canvas 压缩图片的常见做法。

获取图像信息后，就可以对图片进行像素遍历处理。如前所述，需要对相近色进行提取并计算平均值，最终得到主题色和次主题色。

关键问题在于如何定义 " 相近色 "。直接在 RGB 颜色空间中计算颜色差异是不合适的，因为这涉及到感知均匀性的问题 [^2]。

> [!NOTE] 感知均匀性
> XYZ 系统和在它的色度图上表示的两种颜色之间的距离与颜色观察者感知的变化不一致，这个问题叫做感知均匀性 (perceptual uniformity) 问题，也就是颜色之间数字上的差别与视觉感知不一致。由于我们需要在颜色簇中计算出平均色，那么对于人眼来说哪些颜色是相近的？此时，我们需要把 sRGB 转化为 Lab 色彩空间（感知均匀的），再计算其欧氏距离，在某一阈值内的颜色，即可认为是相近色。

因此，需要将 RGB 颜色空间转换为 Lab 颜色空间：

```typescript
// 将 sRGB 转换为 Lab 色彩空间
function rgbToLab(r: number, g: number, b: number): [number, number, number] {
  let R = r / 255,
    G = g / 255,
    B = b / 255
  R = R > 0.04045 ? Math.pow((R + 0.055) / 1.055, 2.4) : R / 12.92
  G = G > 0.04045 ? Math.pow((G + 0.055) / 1.055, 2.4) : G / 12.92
  B = B > 0.04045 ? Math.pow((B + 0.055) / 1.055, 2.4) : B / 12.92

  let X = R * 0.4124 + G * 0.3576 + B * 0.1805
  let Y = R * 0.2126 + G * 0.7152 + B * 0.0722
  let Z = R * 0.0193 + G * 0.1192 + B * 0.9505

  X = X / 0.95047
  Y = Y / 1.0
  Z = Z / 1.08883

  const f = (t: number) => (t > 0.008856 ? Math.pow(t, 1 / 3) : 7.787 * t + 16 / 116)
  const fx = f(X)
  const fy = f(Y)
  const fz = f(Z)
  const L = 116 * fy - 16
  const a = 500 * (fx - fy)
  const bVal = 200 * (fy - fz)
  return [L, a, bVal]
}
```

该函数执行以下步骤：

1. 获取 RGB 参数。
2. 转换为线性 RGB（移除 Gamma 矫正）。常量 0.04045 是 sRGB 颜色空间中的一个阈值，用于区分线性和非线性的 sRGB 值。
3. 将线性 RGB 转换为 XYZ 空间。
4. 归一化 XYZ 值，参考标准白点 D65[^3]。
5. 将 XYZ 转换为 Lab 颜色空间。
6. 计算 L、a 和 b 分量。

    - L：亮度分量。
    - a：绿色到红色的色差分量。
    - b：蓝色到黄色的色差分量。

接下来，实现聚类算法：

```typescript
/**
 * 对满足条件的像素进行聚类
 * @param imageData 图片像素数据
 * @param condition 判断像素是否属于指定区域的条件函数（参数 x, y）
 * @param threshold Lab 距离阈值，低于此值的颜色归为同一簇，建议 8~12
 */
function clusterPixelsByCondition(imageData: ImageData, condition: (x: number, y: number) => boolean, threshold: number = 10): Cluster[] {
  const clusters: Cluster[] = []
  const data = imageData.data
  const width = imageData.width
  const height = imageData.height
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      if (!condition(x, y)) continue
      const index = (y * width + x) * 4
      if (data[index + 3] === 0) continue // 忽略透明像素
      const r = data[index]
      const g = data[index + 1]
      const b = data[index + 2]
      const lab = rgbToLab(r, g, b)
      let added = false
      for (const cluster of clusters) {
        const d = labDistance(lab, cluster.averageLab)
        if (d < threshold) {
          cluster.count++
          cluster.sumRgb[0] += r
          cluster.sumRgb[1] += g
          cluster.sumRgb[2] += b
          cluster.sumLab[0] += lab[0]
          cluster.sumLab[1] += lab[1]
          cluster.sumLab[2] += lab[2]
          cluster.averageRgb = [cluster.sumRgb[0] / cluster.count, cluster.sumRgb[1] / cluster.count, cluster.sumRgb[2] / cluster.count]
          cluster.averageLab = [cluster.sumLab[0] / cluster.count, cluster.sumLab[1] / cluster.count, cluster.sumLab[2] / cluster.count]
          added = true
          break
        }
      }
      if (!added) {
        clusters.push({
          count: 1,
          sumRgb: [r, g, b],
          sumLab: [lab[0], lab[1], lab[2]],
          averageRgb: [r, g, b],
          averageLab: [lab[0], lab[1], lab[2]]
        })
      }
    }
  }
  return clusters
}
```

该函数内部调用了 `labDistance` 函数，用于计算 Lab 颜色空间中的欧氏距离 [^4]：

```typescript
// 计算 Lab 空间的欧氏距离
function labDistance(lab1: [number, number, number], lab2: [number, number, number]): number {
  const dL = lab1[0] - lab2[0]
  const da = lab1[1] - lab2[1]
  const db = lab1[2] - lab2[2]
  return Math.sqrt(dL * dL + da * da + db * db)
}
```

> [!NOTE] 欧氏距离
> 欧氏距离（Euclidean Distance）是一种在多维空间中测量两点之间直线距离的方法。

总体而言，`clusterPixelsByCondition` 函数采用类似于 K-means 算法 [^5] 的聚类方法，将小于用户指定阈值的颜色归为一簇，并计算平均颜色（使用 Lab 值）。

> [!NOTE] 聚类算法
> 聚类算法（Clustering Algorithm）是一种无监督学习方法，用于将数据集中的元素分成不同的组（簇），使得同一组内的元素相似度较高，而不同组之间的元素相似度较低。

> [!NOTE] 颜色簇
> 颜色簇是聚类算法中一个常见的概念，可以理解为 " 一类 " 颜色。

得到颜色簇集合后，就可以根据簇的大小（`count`）来确定主题色：

```typescript
  // 对全图所有像素进行聚类
  let clusters = clusterPixelsByCondition(imageData, () => true, threshold.primary)
  clusters.sort((a, b) => b.count - a.count)
  const primaryCluster = clusters[0]
  const secondaryCluster = clusters.length > 1 ? clusters[1] : clusters[0]
  const primaryColor = rgbToHex(primaryCluster.averageRgb)
  const secondaryColor = rgbToHex(secondaryCluster.averageRgb)
```

至此，已经成功提取了主题色和次主题色。

接下来，计算边缘颜色。

采用类似的方法，但将阈值设置得更小（例如，1）：

```typescript
  // 分别对上、右、下、左边缘进行聚类
  const topClusters = clusterPixelsByCondition(imageData, (_x, y) => y < margin, threshold.top)
  topClusters.sort((a, b) => b.count - a.count)
  const topColor = topClusters.length > 0 ? rgbToHex(topClusters[0].averageRgb) : primaryColor

  const bottomClusters = clusterPixelsByCondition(imageData, (_x, y) => y >= height - margin, threshold.bottom)
  bottomClusters.sort((a, b) => b.count - a.count)
  const bottomColor = bottomClusters.length > 0 ? rgbToHex(bottomClusters[0].averageRgb) : primaryColor

  const leftClusters = clusterPixelsByCondition(imageData, (x, _y) => x < margin, threshold.left)
  leftClusters.sort((a, b) => b.count - a.count)
  const leftColor = leftClusters.length > 0 ? rgbToHex(leftClusters[0].averageRgb) : primaryColor

  const rightClusters = clusterPixelsByCondition(imageData, (x, _y) => x >= width - margin, threshold.right)
  rightClusters.sort((a, b) => b.count - a.count)
  const rightColor = rightClusters.length > 0 ? rgbToHex(rightClusters[0].averageRgb) : primaryColor
```

通过以上代码，可以获取到图片上下左右四个边缘的颜色。

最后，将需要的属性导出，完整的 `colorPicker` 函数如下：

```typescript
/**
 * 主函数：根据图片自动提取颜色
 * @param imageSource 图片 URL 或 HTMLImageElement
 * @returns 返回包含主要颜色、次要颜色和背景色对象（上、右、下、左）的结果
 */
export default async function colorPicker(imageSource: HTMLImageElement | string, options?: autoColorPickerOptions): Promise<AutoHueResult> {
  const { maxSize, threshold } = __handleAutoHueOptions(options)
  const img = await loadImage(imageSource)
  // 降采样（最大尺寸 100px，可根据需求调整）
  const imageData = getImageDataFromImage(img, maxSize)

  // 对全图所有像素进行聚类
  let clusters = clusterPixelsByCondition(imageData, () => true, threshold.primary)
  clusters.sort((a, b) => b.count - a.count)
  const primaryCluster = clusters[0]
  const secondaryCluster = clusters.length > 1 ? clusters[1] : clusters[0]
  const primaryColor = rgbToHex(primaryCluster.averageRgb)
  const secondaryColor = rgbToHex(secondaryCluster.averageRgb)

  // 定义边缘宽度（单位像素）
  const margin = 10
  const width = imageData.width
  const height = imageData.height

  // 分别对上、右、下、左边缘进行聚类
  const topClusters = clusterPixelsByCondition(imageData, (_x, y) => y < margin, threshold.top)
  topClusters.sort((a, b) => b.count - a.count)
  const topColor = topClusters.length > 0 ? rgbToHex(topClusters[0].averageRgb) : primaryColor

  const bottomClusters = clusterPixelsByCondition(imageData, (_x, y) => y >= height - margin, threshold.bottom)
  bottomClusters.sort((a, b) => b.count - a.count)
  const bottomColor = bottomClusters.length > 0 ? rgbToHex(bottomClusters[0].averageRgb) : primaryColor

  const leftClusters = clusterPixelsByCondition(imageData, (x, _y) => x < margin, threshold.left)
  leftClusters.sort((a, b) => b.count - a.count)
  const leftColor = leftClusters.length > 0 ? rgbToHex(leftClusters[0].averageRgb) : primaryColor

  const rightClusters = clusterPixelsByCondition(imageData, (x, _y) => x >= width - margin, threshold.right)
  rightClusters.sort((a, b) => b.count - a.count)
  const rightColor = rightClusters.length > 0 ? rgbToHex(rightClusters[0].averageRgb) : primaryColor

  return {
    primaryColor,
    secondaryColor,
    backgroundColor: {
      top: topColor,
      right: rightColor,
      bottom: bottomColor,
      left: leftColor
    }
  }
}
```

该函数接受 `maxSize`（压缩大小，用于降采样）和 `threshold`（阈值，用于设置簇大小）参数，并允许用户自定义这些参数。为了提高用户友好性，`threshold` 参数支持以下两种类型：

```typescript
type thresholdObj = { primary?: number; left?: number; right?: number; top?: number; bottom?: number }
```

用户可以单独设置主阈值以及上下左右四个边缘的阈值，以适应更个性化的需求.

## autohue.js 发布

`autohue.js` 秉承 auto 家族的命名习惯，其中 hue (色相) 一词简洁易记，且与插件的功能密切相关。

- GitHub 仓库：[GitHub autohue.js](https://github.com/username/autohue.js)
- NPM 包： [NPM autohue.js](https://www.npmjs.com/package/autohue.js)
- 在线体验：[autohue.js 官方首页](https://autohuejs.example.com)

### 安装与使用

```shell
pnpm i autohue.js
```

```typescript
import autohue from 'autohue.js'

autohue(url, {
  threshold: {
    primary: 10,
    left: 1,
    bottom: 12
  },
  maxSize: 50
})
  .then((result) => {
    // 使用 console.log 打印出色块元素s
    console.log(`%c${result.primaryColor}`, 'color: #fff; background: ' + result.primaryColor, 'main')
    console.log(`%c${result.secondaryColor}`, 'color: #fff; background: ' + result.secondaryColor, 'sub')
    console.log(`%c${result.backgroundColor.left}`, 'color: #fff; background: ' + result.backgroundColor.left, 'bg-left')
    console.log(`%c${result.backgroundColor.right}`, 'color: #fff; background: ' + result.backgroundColor.right, 'bg-right')
    console.log(`%clinear-gradient to right`, 'color: #fff; background: linear-gradient(to right, ' + result.backgroundColor.left + ', ' + result.backgroundColor.right + ')', 'bg')
    bg.value = `linear-gradient(to right, ${result.backgroundColor.left}, ${result.backgroundColor.right})`
  })
  .catch((err) => console.error(err))
```

## 效果展示

![复杂边缘效果](https://cdn.widiazine.com/obsidian/f250779e593c4d3f9a10e8f623dc8021.webp)

![纵向渐变效果](https://cdn.widiazine.com/obsidian/47be01ea67bc466695d0c16741933635.webp)

> [!TIP]
> 纵向渐变效果，这里使用的是 left 和 right 边的值，可能使用 top 和 bottom 效果更佳。

![纯色效果](https://cdn.widiazine.com/obsidian/ed273791c06a49a3923acb7e2c08463e.webp)

> [!TIP]
> 纯色效果，因为单独对边缘采样，所以无论图片内容多复杂，纯色基本看不出边界。

![突变边缘效果](https://cdn.widiazine.com/obsidian/254f1a8825d9437393f7ab4e448ea960.webp)

> [!TIP]
> 突变边缘效果，此时用 css 做渐变蒙层应该效果会更好。

![横向渐变效果](https://cdn.widiazine.com/obsidian/17e58028d2324cf98131dd6f6b7dd41e.webp)

> [!TIP]
> 横向渐变效果，使用的是 left 和 right 的色值，基本看不出边界。

## 参考资料

- <https://zhuanlan.zhihu.com/p/370371059>
- <https://baike.baidu.com/item/>国际照明委员会/10021151?fromtitle=CIE&fromid=8649998
- <https://baike.baidu.com/item/>标准光源 D65/20792406
- <https://zh.wikipedia.org/wiki/>欧几里得距离
- <https://blog.csdn.net/weixin>\_42560067/article/details/116182991
- <https://zh.wikipedia.org/wiki/K->平均算法
- <https://blog.csdn.net/weixin>\_42998707/article/details/108011092
- <https://juejin.cn/post/6844903511956815885>

```js


[^1]:  [CIE L*a*b*色彩空间](https://baike.baidu.com/item/%E5%9B%BD%E9%99%85%E7%85%A7%E6%98%8E%E5%A7%94%E5%91%98%E4%BC%9A/10021151?fromtitle=CIE&fromid=8649998)
[^2]:  [感知均匀性问题](https://zhuanlan.zhihu.com/p/370371059)
[^3]:  [标准光源D65](https://baike.baidu.com/item/%E6%A0%87%E5%87%86%E5%85%89%E6%BA%90%20D65/20792406)
[^4]:  [欧几里得距离](https://zh.wikipedia.org/wiki/%E6%AC%A7%E5%87%A0%E9%87%8C%E5%BE%97%E8%B7%9D%E7%A6%BB)
[^5]:  [K-means算法](https://zh.wikipedia.org/wiki/K-%E5%B9%B3%E5%9D%87%E7%AE%97%E6%B3%95)
