Search code examples
imagemagickdraw

How can I draw multiple overlay rectangles on an image using ImageMagick


I use the following code to draw an overlay box over another image

        convert                 \
         -background '#0002'    \
         -gravity Center        \
         -fill white            \
         -size ${page_width}x30     \
          caption:""      \
          "${img}"              \
         +swap                  \
         -geometry +0+100            \
         -composite             \
          "${img}"  

however, I want to draw it on multiple positions, for example every other 100 pixels from top to the bottom of the image. I can use a loop for this purpose, but I would like to know if there is a better command or solution for this problem?


Solution

  • You can do that by tiling your pattern over the image using Imagemagick.

    • Create a "#0002" image using -size ... xc:"#0002"
    • Create a fully transparent image of the height of your spacing in a similar manner
    • Append the two images vertically
    • Tile them out over the size of the input image
    • Composite that over the input image

    Input:

    enter image description here

    # Line 1: read the input
    # Line 2: create the tile (spacing set to 50 in transparent section)
    # Line 3: tile it out over the size of the input by replacing it on the input
    # Line 4: do the composite
    # Line 5: save the output
    
    convert lena.png \
    \( -size 256x30 xc:"#0002" -size 256x50 xc:none -append -write mpr:tile +delete \) \
    \( -clone 0 -tile mpr:tile -draw "color 0,0 reset" \) \
    -compose over -composite \
    result.png
    


    Result:

    enter image description here