簡體   English   中英

如何找到正確的圖像尺寸

[英]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()

結果: 在此處輸入圖片說明

一種方法是將size乘以\\n的出現次數。

n = text.count('\n') + 2
# create image
image = Image.new(mode = "RGB", size = (int(size/2)*len(text),size*n), color = bg)

結果:


在此處輸入圖片說明

如果從文本中刪除\\n ,結果將是:

在此處輸入圖片說明

其他例子:

在此處輸入圖片說明

在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM