Class ColorExtractor

java.lang.Object
cloud.opencode.base.image.color.ColorExtractor

public final class ColorExtractor extends Object
Color Extraction Utility 颜色提取工具类

Extracts dominant colors from rasters using a simplified K-Means clustering algorithm on downsampled pixel data. Colors are returned as packed ARGB int values (alpha = 0xFF).

使用简化的 K-Means 聚类算法对降采样像素数据提取主色调。颜色以打包的 ARGB int(alpha = 0xFF)返回。

Features | 主要功能:

  • Extract multiple dominant colors via K-Means - 通过 K-Means 提取多个主色调
  • Extract single dominant color - 提取单个主色调
  • 64x64 downsampling for performance - 64x64 降采样以提升性能

Usage Examples | 使用示例:

// Extract top 5 dominant colors as packed ARGB ints
List<Integer> colors = ColorExtractor.dominantColors(raster, 5);

// Extract the single most dominant color
int primary = ColorExtractor.dominantColor(raster);
int r = (primary >>> 16) & 0xFF;

Performance | 性能特性:

  • Time: O(k * iter * n) where n = 64*64 samples, k = cluster count, iter = max 20 - 时间: O(k * iter * n)
  • Space: O(n + k) - 空间: O(n + k)

Security | 安全性:

  • Thread-safe: Yes (stateless) - 线程安全: 是(无状态)
  • Null-safe: No - 空值安全: 否
Since:
JDK 25, opencode-base-image V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • dominantColors

      public static List<Integer> dominantColors(Raster raster, int count)
      Extract the dominant colors from a Raster using K-Means clustering. 使用 K-Means 聚类从 Raster 中提取主色调列表。

      The raster is first downsampled to 64x64 via nearest-neighbor sampling, then K-Means clustering is applied. Results are returned as packed ARGB int values sorted by cluster size (most dominant first).

      raster 首先通过最近邻采样降采样到 64x64,然后使用 K-Means 聚类。结果以 打包 ARGB int 返回,按聚类大小降序排列。

      Parameters:
      raster - the source raster | 源 raster
      count - the number of dominant colors to extract, must be in [1, 20] | 主色调数量,[1, 20]
      Returns:
      the list of dominant colors (packed ARGB ints) sorted by prevalence | 按主要程度排序的主色调列表(打包 ARGB int)
      Throws:
      NullPointerException - if raster is null | 当 raster 为 null 时抛出
      ImageOperationException - if count is out of [1, 20] range | count 超出范围时抛出
      Since:
      opencode-base-image V1.0.4
    • dominantColor

      public static int dominantColor(Raster raster)
      Extract the single most dominant color from a Raster. 从 Raster 中提取单个最主要的颜色。

      Returns the packed ARGB int (alpha=0xFF) of the most dominant cluster.

      返回最主要聚类的打包 ARGB int(alpha=0xFF)。

      Parameters:
      raster - the source raster | 源 raster
      Returns:
      the most dominant color as a packed ARGB int | 最主要的颜色(打包 ARGB int)
      Throws:
      NullPointerException - if raster is null | 当 raster 为 null 时抛出
      Since:
      opencode-base-image V1.0.4