如何从脚本的纯色图像中获取十六进制颜色代码?

How to get a Hex Color Code from a solid-color image for a script?

我正在编写一个脚本,将 Linux 机器上的背景更改为一组仅包含纯色的图像中的随机图像。我想做的是扩展这个脚本以相应地为某些应用程序(主要是终端应用程序)设置主题,至少要更改文本颜色,可能从深色背景切换到浅色背景等。我想知道我有什么选择获取图像中颜色的十六进制代码。 bash 中有什么东西可以用吗?我是否需要用更健壮的语言编写程序并将十六进制代码作为输出?有没有更好的方法来完全做到这一点?到目前为止,我的搜索有点不确定。

我强烈推荐使用 ImageMagick for this task. The documentation 提到了如何从图像中提取数据。

来自 "Extracting the average colour":

The average color of an image can be found very quickly by using "-scale" to reduce an image to a single pixel. Here for example is the average color of the built-in "rose:" image. I output the color using the FX Escape Format which returns a color string that can be used directly IM without change.

user@laptop:~$ convert rose: -scale 1x1\! -format '%[pixel:s]\n' info:-

Will output: srgb(146,89,80)

在您的情况下,将 rose: 替换为您的图像文件,例如 foo.png

如果你想直接以十六进制表示输出,使用这个:

convert rose: -scale 1x1\! -format '%[pixel:s]\n' info:- | awk -F '[(,)]' '{printf("#%x%x%x\n",,,)}'