Search code examples
batch-fileimagemagickpixel

Imagemagick convert opaque pixels to specific color


I would like to batch convert a bundle of PNG files using ImageMagick in aim to change all opaque pixels in each image to specific hexa color.

I tried

for f in *.png; do convert "$f" -colorspace Gray -auto-level "${file%%.png}_gray.png"; done

result of just one image converted where all opaque pixels converted to white

I tried without batching , each command successfully done but always wite pixels.

How could I do to set opaque pixels to #AAA ?

Thanks!


Solution

  • When you say opaque pixels, I am not sure if you mean pixels with 100% opacity or pixels with non-zero transparency.

    Method 1

    So, if we start with this image which is a blue square with a transparent surround and a further blue surround:

    enter image description here

    Then we can make the non-transparent pixels yellow with:

    convert image.png -fill yellow -colorize 100% result.png
    

    enter image description here

    You would use '#AAA' in place of yellow.

    Method 2

    Another way of thinking about it is to set each RGB pixel to 10/16, i.e. A on a hex scale:

    convert image.png -channel RGB -fx '10/16' result.png
    

    enter image description here

    Method 3

    Or you may have mean that if you start with this - which is a gradient from transparent at the top to black with a red border:

    enter image description here

    then you want all except the fully transparent pixels (near the top) to become #AAA (shown here with yellow instead):

    convert start.png -channel A -threshold 1 -channel RGB -fill yellow -colorize 100% result.png
    

    enter image description here