Oct 15, 2024

Linux: find all images in a directory with a pixel of a particular color value

(Image created using DALLĀ·E by OpenAI) 

We had a unique client task that required us to search a vast library of images that happened to contain a very specific color (by RGB value). These images would need to be updated for the current branding color. We started by trying to eyeball image swatches, but then found there were far too many to search manually.

Using ImageMagick, available on most Linux/Unix installations, the following script will search a directory for images that contain a matching color. The color is set in a shell script variable, $color_to_search.

First, create the shell script, such as find_color.sh.

#!/bin/bash
color_to_search="255,0,0" # Replace with the RGB color you want to find
directory=$1
for image in "$directory"/*; do
    if [[ $image == *.png || $image == *.jpg || $image == *.jpeg ]]; then
        # Extract pixel color information
        colors=$(convert "$image" -format "%c" histogram:info:- | awk '{print $2}')
        if echo "$colors" | grep -q "$color_to_search"; then
            echo "Found color in $image"
        fi
    fi
done

Next, give the script execute permissions:

chmod +x find_color.sh

Finally, run the script:

./find_color.sh /path/to/directory

Voila! A list will begin to generate with the path to matching images:

Found color in uploads/blog_images/california-equation-im.png
Found color in uploads/blog_images/california-equation-si.png
Found color in uploads/blog_images/california-imperial-equation.png
Found color in uploads/blog_images/custom-flow-equations.png
Found color in uploads/blog_images/custom-cutthroat-flume-submerged-flow-equations.png
Found color in uploads/blog_images/free-equation-e.png
Found color in uploads/blog_images/get_help.png
Found color in uploads/blog_images/discharge-equation-b.png
Found color in uploads/blog_images/short-form-discharge-equation.png

Note: when choosing an RGB color (using Photoshop or something similar), note that a PNG file may differ in RGB value from a JPG file, though to the naked eye the color may look the same.

This method would work for CSS and SVG files, but all one would need is a text search (grep, for example). Searching PDF images would technically be possible using pdfgrep or pdftotext.

Want to share this post?