[英]How to find the correct Image size
我正在嘗試在 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.