There's some trigonometry involved in finding a general solution for this problem.
In this diagram:
the final result that is required is the rectangle with dimensions w by h which is outlined in yellow.
It is cropped from a larger rotated rectangle containing the gradient.
If the angle of rotation is "theta" degrees clockwise then the length of the long side of this rectangle is w*cos(theta)+h*sin(theta) as shown in the diagram. The length of the other side is w*sin(theta)+h*cos(theta). In principle what we need to do is create this larger rectangle with the gradient, rotate it and then crop out the rectangle we need but with this sort of calculation involved there's no way you can do it without using some sort of script or program.
I wrote a C program which creates the gradient and then uses affine transforms to shift it so that its centre is at 0,0, rotate it and then shift it back again. It then crops the required rectangle. The resulting rectangle has at least one white pixel at the top right and one black pixel at the bottom left.
I also tried scripting it (using TCL) to use a command line call to convert. In this case I did things a different way. It rotates the gradient around the top left corner (the ImageMagick origin) and then crops the gradient from the middle. It doesn't work out as precisely as the C program because either the bottom left pixel isn't pure black or the top right pixel isn't pure white. But it is close.
Here's the TCL code. I can post the (larger) C code if someone wants it.
Code: Select all
# Dimensions of final rectangle
set w 600
set h 100
# rotation angle in degrees
set theta 15
# Convert degrees to radians
set rad_theta [expr $theta*4*atan(1.)/180.]
# Compute the dimensions needed for the rectangular gradient so that it will
# hold the final image after rotation
set gh [expr int($w*sin($rad_theta) + $h*cos($rad_theta) + 0.5)]
set gw [expr int($w*cos($rad_theta) + $h*sin($rad_theta) + 0.5)]
# Execute the convert program (called imconvert here to avoid conflict with the Windows convert command)
exec imconvert ( -size $gw\x$gh gradient:white-black -write rotgrad_g.png +distort SRT $theta -write rotgrad_b.png ) +repage -gravity center -crop $w\x$h+0+0 +repage rotgrad.png
Pete