Search code examples
imagemagicknine-patchimagemagick-convert

Specify endpoints of lines by percentage of image size


I'm trying to draw the stretch bars on various sizes of ninepatch images. I'm doing this in a script, and I'd like to be able to specify a different master image or scale it to a different size without manually recalculating all the pixel coordinates of the lines I'm drawing on it. Is there a way to specify the endpoints of lines as a percentage of the image size? I tried this, which does not work:

convert -draw 'line 0,45% 0,55%' $myfile tmp~ && mv tmp~ $myfile

I had hoped this would draw a line along the middle 10% of the left side of the image. It does draw a line, but it ignores the percents and draws the line from 0,45 to 0,55 regardless of the image size.

If this is not possible with ImageMagick, is there another Linux command-line tool I could use?


Solution

  • I don't believe you can do that using percentages, but you can get it pretty succinct and avoid having to do any calculations using bash or bc or somesuch by using ImageMagick's built-in fx operator to calculate the line position as a function of the image height.

    The best I can come up with is this:

    linespec=$(convert image.jpg -format "0,%[fx:int(h*0.45)],0,%[fx:int(h*0.55)]" info:)
    convert image.jpg -stroke red -strokewidth 32 -draw "line $linespec" image.jpg
    

    Of course you can replace image.jpg with a variable, and you can also make it an (ugly) one-liner by putting the first command in the middle of the second if you really want to.

    Note also, that there is no need to create a temporary image and rename like you do - you can just draw on your original like I have.