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

时间:2017-04-30 04:50:00

标签: python python-imaging-library 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.

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

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

任何人都可以帮我指出问题吗?位置(或偏移)有问题吗?我pasting错了吗? 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

1 个答案:

答案 0 :(得分:1)

问题在于offsetdocs Image.paste说:

  

如果使用2元组,则将其视为左上角。

因此,使用(img_width/2, img_height/2),您可以在大图像中间的左上角粘贴条带。这里贴着" foo bar"在您的示例图片上:

With original code

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

With new offset

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