How to apply a gradient to an image in ImageMagick?

0

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.

artfulrobot

Posted 2016-09-21T11:49:09.950

Reputation: 197

Answers

0

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.

artfulrobot

Posted 2016-09-21T11:49:09.950

Reputation: 197

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? – μολὼν.λαβέ – 2017-12-05T01:37:29.330

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 – 2017-12-05T12:50:52.670