繁体   English   中英

我将如何使用 PIL 来“扩展”图像,然后绘制一个带有文本的黑色矩形?

[英]How would I use PIL to "extend" an image, and then draw a black rectangle with text on it?

基本上,我想用 Pillow 做的是:

我想要一张图片,然后从底部扩展图片的大小,这样我就可以在上面放置一个带有四位代码的黑色矩形。 我该怎么做? 我试过了,但出于某种原因,我的文字最终变得非常小且难以阅读,而且我的矩形也不完美。

如果它更容易,这是我的图片: https://i.stack.imgur.com/o9eYr.jpg

这就是我想要的最终结果: https://i.stack.imgur.com/GZ4uu.jpg (看看图片的底部)

我建议ImageOps.expand扩展你的 canvas:

#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageFont, ImageOps

# Load image
im = Image.open('o9eYr.jpg')

# Define font size, and annotation and height of padding above and below annotation
fontSize   = 130
annotation = "GVVL"
padding    = 20

# Load font and work out size of annotation
font = ImageFont.truetype("/System/Library/Fonts//Menlo.ttc", fontSize)
tw, th = font.getsize(annotation)

# Extend image at bottom and get height and width of new canvas
extended = ImageOps.expand(im, border=(0,0,0,th+2*padding), fill=(0,0,0))
w, h = extended.size

# Get drawing context and annotate
draw = ImageDraw.Draw(extended)
draw.text(((w-tw)//2, h-th-padding), annotation,(255,255,255),font=font)
extended.save('result.jpg')

在此处输入图像描述

您可以创建一个新的黑色图像,粘贴所需的图像并添加文本。

from PIL import Image, ImageFont, ImageDraw    

base_img = Image.open('tmp.jpg')
base_size = base_img.size
new_size = (base_size[0], base_size[1] + 150)
img = Image.new("RGB", new_size)
img.paste(base_img, (0, 0))

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("microsoftsansserif.ttf", 145) # (<font-file>, <font-size>)d
draw.text((base_size[0] // 2 - 150, base_size[1]),"GVVL",(255,255,255),font=font) # (x, y),"text",(r,g,b)
img.save('out.jpg')

结果:

结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM