Home>

I generated a character image with python3.7 pillow, but I would like to adjust the size so that it matches the vertical width, but the generated image is stacked in a flat manner from the 0 point. I'm in trouble.

At first, I tried to change the vertical/horizontal size of the image with img.resize or img.thumbnail, but I changed the original size from 128x128, so I asked if it was fundamentally different.

txt = "That"
fontsize = 30
img = Image.new ('RGBA', (128, 128), (255, 255, 255))
draw = ImageDraw.Draw (img)
font_path = "/static/font/font.otf"
font = ImageFont.truetype (font_path, fontsize)
draw = ImageDraw.Draw (img)
draw.text ((0, 0), txt, fill = '# 000', font = font)
img.save ('hello.png')


Above output contents

Does it extend as follows? I want the image to be

  • Answer # 1

    What about this? Although the resolution drops considerably.

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    txt = "That"
    fontsize = 30
    #Create an image with the size before enlargement
    img = Image.new ('RGBA', (128, fontsize), (255, 255, 255))
    draw = ImageDraw.Draw (img)
    font_path = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
    font = ImageFont.truetype (font_path, fontsize)
    draw = ImageDraw.Draw (img)
    draw.text ((0, 0), txt, fill = '# 000', font = font)
    # Stretch image vertically
    img2 = img.resize ((128,128))
    img2.save ('hello.png')

    If you use the ratio as follows, you can also generate without reducing the resolution.

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    txt = "That"
    fontsize = 30
    ratio = 3
    #Create an image with the size before enlargement
    img = Image.new ('RGBA', (128 * ratio, fontsize * ratio), (255, 255, 255))
    draw = ImageDraw.Draw (img)
    font_path = "/usr/share/fonts/OTF/TakaoPMincho.ttf"
    font = ImageFont.truetype (font_path, fontsize * ratio)
    draw = ImageDraw.Draw (img)
    draw.text ((0, 0), txt, fill = '# 000', font = font)
    # Stretch image vertically
    img2 = img.resize ((128,128))
    img2.save ('hello.png')