uni-app 实现图片主题色的获取

<canvas canvas-id="getImageThemeColorCanvas" id="getImageThemeColorCanvas">
</canvas>

canvas 元素默认宽为 300,高为 150。需要注意的是,上述代码不可或缺。

/**
 * 获取图片主题色
 * @param path
 * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径
 * @param canvasId
 * 画布表示
 * @param callback
 * 回调函数,返回图片主题色的 RGB 颜色值
 */
function getImageThemeColor(path, canvasId, callback) {
  uni.getImageInfo({
    src: path,
    success: function (img) {
      // 创建一个 Canvas 对象
      const ctx = uni.createCanvasContext(canvasId);
      // 将图片绘制到 Canvas 上
      const imgWidth = 300;
      const imgHeight = 150;
      ctx.drawImage(img.path, 0, 0, imgWidth, imgHeight);
      ctx.save();
      ctx.draw(true, () => {
        uni.canvasGetImageData({
          canvasId: canvasId,
          x: 0,
          y: 0,
          width: imgWidth,
          height: imgHeight,
          success(res) {
            let data = res.data;
            let arr = [];
            let r = 1,
              g = 1,
              b = 1;
            // 取所有像素的平均值
            for (let row = 0; row < imgHeight; row++) {
              for (let col = 0; col < imgWidth; col++) {
                if (row == 0) {
                  r += data[imgWidth * row + col];
                  g += data[imgWidth * row + col + 1];
                  b += data[imgWidth * row + col + 2];
                  arr.push([r, g, b]);
                } else {
                  r += data[(imgWidth * row + col) * 4];
                  g += data[(imgWidth * row + col) * 4 + 1];
                  b += data[(imgWidth * row + col) * 4 + 2];
                  arr.push([r, g, b]);
                }
              }
            }
            // 求取平均值
            r /= imgWidth * imgHeight;
            g /= imgWidth * imgHeight;
            b /= imgWidth * imgHeight;
            // 将最终的值取整
            r = Math.round(r);
            g = Math.round(g);
            b = Math.round(b);

            if (!!callback) {
              // 返回图片主题色的 RGB 颜色值
              callback(`${r},${g},${b}`);
            }
          },
        });
      });
    },
  });
}

上述代码通过使用 uni-app 的 API uni.getImageInfouni.createCanvasContextuni.canvasGetImageData 实现图片主题色获取,以兼容 H5 和 微信小程序等,并以 canvas 默认的宽高进行绘制。

调用示例:

const imgUrl = "https://image.net/path/abc.jpg";
getImageThemeColor(imgUrl, "getImageThemeColorCanvas", (retRGBColor) => {
  console.log("retRGBColor", retRGBColor);
});