首页 > 解决方案 > 如何找到正确的图像尺寸

问题描述

我正在尝试在 Python 中将文本转换为图像

这是代码:只要文本是单行的,

例如“要在 img 1234567890 上书写的文字”

没事 在此处输入图像描述

但如果文本包含“\n”,则图像剪辑和大小计算将不正确

“要写在 \n img 1234567890 上的文字”

在此处输入图像描述

请帮忙

import numpy as np
import time
import text_to_image
from PIL import Image, ImageDraw, ImageFont
import os
from win32api import GetSystemMetrics


def text_on_img(filename='01.png', text="Text to write on \n img 1234567890", size=200, color=(0,0,0), bg='white'):
    "Draw a text on an Image, saves it, show it"
    fnt = ImageFont.truetype('arial.ttf', size)
    # create image
    image = Image.new(mode = "RGB", size = (int(size/2)*len(text),size+50), color = bg)
    draw = ImageDraw.Draw(image)
    # draw text
    draw.text((10,10), text, font=fnt, fill=(0,0,0))
    # save file
    image.save(filename)
    # show file
    os.system(filename)


text_on_img()

标签: python

解决方案


我完美地修复了它。请测试一下。

import os

from PIL import Image, ImageDraw, ImageFont


def text_on_img(filename='01.png', text="Text to write on \n img 1234567890", size=200, color=(0, 0, 0), bg='white'):
    "Draw a text on an Image, saves it, show it"
    fnt = ImageFont.truetype('arial.ttf', size)
    # create image

    width = max([int(size/2) * len(line) for line in text.split('\n')])
    height = (size + 50) * len(text.split('\n'))

    image = Image.new(mode="RGB", size=(width, height), color=bg)
    draw = ImageDraw.Draw(image)
    # draw text
    draw.text((10, 10), text, font=fnt, fill=(0, 0, 0))
    # save file
    image.save(filename)
    # show file
    os.system(filename)


text_on_img()

结果: 在此处输入图像描述


推荐阅读