有没有一种方法可以获取Javafx中图像的最主要颜色

问题描述 投票:0回答:1

我正在尝试构建一个应用程序,并且我需要将vbox的背景与附加到其上的图像的最主要颜色相同,现在正在使用随机图像,因此我需要我的程序能够计算这本身。请任何建议

java javafx scenebuilder
1个回答
0
投票

是,但是没有nice方式。

此代码并不完美(我在电话上,但请考虑以下代码:

// Read the image.

final InputStream is = new FileInputStream("Path\\To\\Image");
final Image img = new Image(is);

// Read through the pixels and count the number of occurrences of each color.

final PixelReader pr = img.getPixelReader();
final Map<Color, Long> colCount = new HashMap<>();

for(int x = 0; x < img.getWidth(); x++) {
  for(int y = 0; y < img.getHeight(); y++) {
    final Color col = pr.getColor(x, y);
    if(colCount.containsKey(col)) {
      colCount.put(col, colCount.get(col) + 1);
    } else {
      colCount.put(col, 1L);
    }
  }
}

// Sort the map by its value. The first element is now the dominant color.

final Map<Color, Long> colCountSorted = colCount.entrySet().stream().sorted(Map.Entry.<Color, Long>comparingByValue().reversed()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
final Color dominantCol = colCountSorted.keySet().toArray(new Color[0])[0];
© www.soinside.com 2019 - 2024. All rights reserved.