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

不羁岁月 提交于 2019-12-10 12:22:07

问题


I was writing a script to change my background on my Linux Machine to a random image from a set of images that contain only solid colors. What I would like to do is expand this script to also theme certain applications (mostly terminal ones) accordingly, at the very least to change the text color, possibly switch from dark to light background, etc. I was wondering what options I have to get the Hex Code for the color in the image. Is there something in bash I can do this with? Would I need to write a program in a more robust language and have the hex-code be the output? Is there a better way of doing this entirely? My searching thus far has been a bit inconclusive.


回答1:


I would highly recommend to use ImageMagick for this task. The documentation mentions how to extract data from an image.

From "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)

In your case, replace rose: with an image file of yours, like foo.png.

If you want the output directly in hex notation, use this:

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


来源:https://stackoverflow.com/questions/47982983/how-to-get-a-hex-color-code-from-a-solid-color-image-for-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!