python – 使用PIL / Pillow在基本图像上粘贴叠加(带文本)

我有一个给定的图像.我想创建一个黑色条带作为此图像上的叠加层,文本写在所述条带上.
Here’s是我的意思的视觉例子.

我正在使用Python PIL来实现这一点(在Django项目中),这是我到目前为止所写的内容:

from PIL import Image, ImageFont, ImageDraw

img_width, img_height = img.size #getting the base image's size
if img.mode != 'RGB':
    img = img.convert("RGB")
strip = Image.new('RGB', (img_width, 20)) #creating the black strip
draw = ImageDraw.Draw(strip)
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 16)
draw.text((img_width/2,10),"foo bar",(255,255,255),font=font) #drawing text on the black strip
offset = (img_width/2,img_height/2)
img.paste(strip,offset) #pasting black strip on the base image
# and from here on, I save the image, create thumbnails, etc.

这根本不起作用.如图所示,图像显示没有任何文本或黑色条带,就像它最初一样.

请注意,如果我直接尝试在图像上书写(没有黑色条带),它可以完美地工作.此外,图像处理本身也正常工作(即在我不在图像上写任何东西的情况下).

任何人都可以帮我指出问题吗?位置(或偏移)有问题吗?我贴错了吗? RGB转换是否应该归咎于?或者它完全是另一回事?一个说明性的例子会很棒.顺便说一下,性能也很重要;我试图尽可能无成本地做到这一点.

如果重要,以下是我以后对图像文件的处理方式:

from django.core.files.uploadedfile import InMemoryUploadedFile

img.thumbnail((300, 300))
thumbnailString = StringIO.StringIO()
img.save(thumbnailString, 'JPEG', optimize=True)
newFile = InMemoryUploadedFile(thumbnailString, None, 'temp.jpg','image/jpeg', thumbnailString.len, None)
# and then the image file is saved in a database object, to be served later

最佳答案 问题在于抵消.
docs Image.paste说:

If a 2-tuple is used instead, it’s treated as the upper left corner.

所以使用(img_width / 2,img_height / 2),你将它贴在大图像中间的左上角.在这里,它将“foo bar”粘贴到您的示例图片上:

《python – 使用PIL / Pillow在基本图像上粘贴叠加(带文本)》

如果将其更改为offset =(0,img_height / 2),则会将其粘贴到中间但从左侧开始.这里的“foo bar”粘贴到正确的位置:

《python – 使用PIL / Pillow在基本图像上粘贴叠加(带文本)》

条带可以做得更高(高度可以从给定字体大小的文本计算),文本可以居中,但我希望这些东西已经在Stack Overflow或Pillow docs中的其他地方得到了解答.

点赞