python - 如何找到正确的图像尺寸
问题描述
我正在尝试在 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()
解决方案
我完美地修复了它。请测试一下。
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()
推荐阅读
- shiny - 通过单击多个 div 打开 Shiny Modal 对话框
- javascript - TypeError:无法读取 null 的属性“0”,react-fullpage
- java - 更改 JPEG 图像的 X & Y 密度和颜色深度
- python - 如何修复 AttributeError:“NoneType”对象没有属性“get”
- servicestack - 向社交登录发送附加参数
- java - coverage.ec 文件格式
- c++ - 不引用所有 Gtk::Builder 变量是否明智,因为 Gtk::Application 已经被引用
- c# - 在 Mac 上从 .NET Core 运行进程
- python - 日期时间模块中的 %b vs %B (python 3)
- typescript - 尝试从选择器选项访问日期数组时为空