I have an image and I want to make it lighter at the top fading to no effect at the bottom. So if the image was a solid green to begin with, at the end it would look like a gradient from light green to green.

I thought I could do something like this (copmositing a white block over the top of the image using a gradient as a mask):

convert a.jpg \( +clone -fill white \) \
      \( +clone gradient:white-black  \) \
      -composite out.jpg

Or this ('colorize' an image with a gradient that fades to transparent)

convert a.jpg \( +clone 'gradient:black-rgba(0,0,0,0)' \) \
        -colorize 50% out.jpg

…but neither works.

convert a.jpg \( +clone -fx 'i/w' \) -compose multiply -composite out.jpg

This will take a copy of the image and apply the -fx operator. The forumla i/w goes over every pixel for i = 0 to width w such that at the left (i == 0) the output is zero (black) and at the right (i == w) the output is one (white).

Then compose with multiply so it fades from pure black on left hand side to the pure original at the rightmost edge.

You can also do things like this:

convert a.jpg \( +clone \
  -fx 'i/w < 0.2 ? 0.2 : (i/w -0.2)*4 + 0.2' \
  \) -compose multiply -composite output.jpg

Which will darken the left 20% of the image by 80%, then from 40% from the left it has no effect and between 20% and 40% it linearly fades out.

  • how would you apply it to a masked region like a circle of radius R, while leaving the rest of the image outside the circle transparent? – μολὼν.λαβέ Dec 5 '17 at 1:37
  • You could do it with maths and ternary operators but it would get very complex. Imagemagick probably has a way to draw a circle. So use that inside the \( ... \) bit to create a circle. This case should be a new question really. – artfulrobot Dec 5 '17 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.