我正在尝试在python中为这个meme生成器添加笔画。这段代码会生成一个meme,但不会给它添加笔划。该怎么做呢?当我使用它时,结果图像中只显示白色文本。我想黑色边框文本也。
下面是我的代码:
from PIL import Image, ImageDraw, ImageFont
import textwrap
def generate_meme(image_path, top_text, bottom_text='', font_path='./fonts/impact/impact.ttf', font_size=9):
# load image
im = Image.open(image_path)
draw = ImageDraw.Draw(im)
image_width, image_height = im.size
# load font
font = ImageFont.truetype(font=font_path, size=int(image_height*font_size)//100)
# convert text to uppercase
top_text = top_text.upper()
bottom_text = bottom_text.upper()
# text wrapping
char_width, char_height = font.getsize('A')
chars_per_line = image_width // char_width
top_lines = textwrap.wrap(top_text, width=chars_per_line)
bottom_lines = textwrap.wrap(bottom_text, width=chars_per_line)
# draw top lines
y = 10
for line in top_lines:
line_width, line_height = font.getsize(line)
x = (image_width - line_width)/2
draw.text((x,y), line, fill='white', font=font)
y += line_height
# draw bottom lines
y = image_height - char_height * len(bottom_lines) - 15
for line in bottom_lines:
line_width, line_height = font.getsize(line)
x = (image_width - line_width)/2
draw.text((x,y), line, fill='white', font=font)
y += line_height
# save meme
im.save('meme-' + im.filename.split('/')[-1]) 发布于 2020-11-10 19:28:49
这很简单!在添加白文本之前添加黑色边框这里是代码
def generate_meme(image_path, top_text, bottom_text='', font_path='fonts/impact.ttf', font_size=9):
im = Image.open(image_path)
draw = ImageDraw.Draw(im)
image_width, image_height = im.size
font = ImageFont.truetype(font=font_path, size=int(image_height * font_size) // 100)
top_text = top_text.upper()
bottom_text = bottom_text.upper()
char_width, char_height = font.getsize('A')
chars_per_line = image_width // char_width
top_lines = textwrap.wrap(top_text, width=chars_per_line)
bottom_lines = textwrap.wrap(bottom_text, width=chars_per_line)
y = 10
for line in top_lines:
line_width, line_height = font.getsize(line)
x = (image_width - line_width) / 2
draw.text((x-1, y), line, font=font, fill='black')
draw.text((x+1, y), line, font=font, fill='black')
draw.text((x, y-1), line, font=font, fill='black')
draw.text((x, y+1), line, font=font, fill='black')
draw.text((x, y), line, fill='white', font=font)
y += line_height
y = image_height - char_height * len(bottom_lines) - 15
for line in bottom_lines:
line_width, line_height = font.getsize(line)
x = (image_width - line_width) / 2
draw.text((x-1, y), line, font=font, fill='black')
draw.text((x+1, y), line, font=font, fill='black')
draw.text((x, y-1), line, font=font, fill='black')
draw.text((x, y+1), line, font=font, fill='black')
draw.text((x, y), line, fill='white', font=font)
y += line_height
file_name = "memeimg.png"
ok = sedpath + "/" + file_name
im.save(ok, "PNG")https://stackoverflow.com/questions/64765852
复制相似问题