java - 有没有办法在Javafx中获得图像的最主要颜色

标签 java javafx scenebuilder

我正在尝试构建一个应用程序,我需要我的 vbox 的背景与附加到它的图像的最主要颜色相同,现在正在处理随机图像,所以我需要我的程序能够这个自己算一下。 请提出任何建议

最佳答案

是的,但是没有好的方法来做到这一点。

此代码并不完美(我在手机上),但请考虑以下代码:

// 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);
    }
  }
}

// Get the color with the highest number of occurrences .

final Color dominantCol = colCount.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();

编辑1:

您可能想要实现某种形式的阈值方法。例如,您可以将每种颜色分类为红色、绿色或蓝色(在实际应用中您可能需要更多的色调范围)。然后,使用匹配次数最多的范围的平均值或中位数。

关于java - 有没有办法在Javafx中获得图像的最主要颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59035140/

相关文章:

Java : Swing : Hide frame after button pressed

java - 如何增加 ToggleGroup 中可能选择的数量(例如 RadioButtons)?

java - 线程中出现异常 "JavaFX Application Thread"java.lang.IllegalArgumentException

java - JavaFX中标签的自动换行

java - 如何在maven项目中运行broadleaf commerce开放管理

java - java 8 流 api 中的条件检查

java - 执行请求 关注以编程方式创建的编辑文本

JavaFX:如何制作扩展名为.fx的脚本文件?

multithreading - java.lang.IllegalStateException : Not on FX application thread Calling Function

java - 图像容器