pythonwand

stretch draw text with Python Wand


I am exploring how to get some image manipulation done with Python Wand.

I would like to know how to do a "stretch draw": fit a text with the boundaries of a certain box. In Delphi, this would be done drawing on a canvas, then do a copy onto another canvas.

The process in Python Wand is probably similar, but I have not been able to find the solution yet. Given that I have the following script to create a bunch of identical images with a number:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

imagewidth=1800
imageheight=600

def makeImage(mynr):
    myimage = Image(
        width=imagewidth,
        height=imageheight,
        background=Color("white")
    )
    with Drawing() as draw:
        draw.font="Arial"
        draw.font_size=500
        draw.gravity="center"
        draw.text(0,0,f"{mynr:04d}")
        draw(myimage)

    # -- need to have 1 bit BMP images
    myimage.depth = 2
    myimage.type="bilevel"

    myimage.save(filename=f'test{mynr:02d}.bmp', )
    myimage = None
    print( mynr )  # to see progress

def do_numbers():
    for i in range(30):
        makeImage(i+1)

# ===============
if __name__ == "__main__":
    do_numbers()

I get the following which is drawn OK in the right image format:

Text as drawn by current script

My goal is to have something like this, keeping image size. Text is stretched to fit image.

Text as desired, stretched to fit

(Note: images are scaled to 1/10 for clarity here, so won't match script output)


Solution

  • I think this maybe closer to what you want:

    #!/usr/bin/env python3
    
    from wand.image import Image
    from wand.drawing import Drawing
    from wand.font import Font
    
    w, h = 1800, 600
    
    # Create a white canvas
    with Image(width=w, height=h, pseudo='xc:white') as canvas:
        with Drawing() as context:
            font = Font('/System/Library/Fonts/Supplemental/Verdana.ttf', 0, "lime")
            context(canvas)
            canvas.caption('0025', width=w, height=h, font=font)
        canvas.trim()
        canvas.resize(w,h)
        canvas.save(filename='result.png')
    

    enter image description here


    Note that I had to do the following on macOS to help wand find my ImageMagick installation from homebrew:

    # Help wand find ImageMagick
    export MAGICK_HOME=/opt/homebrew