【问题标题】:Pasting an overlay (with text) on top of a base image, using PIL/Pillow使用 PIL/Pillow 在基础图像上粘贴叠加层(带有文本)
【发布时间】:2017-04-30 04:49:59
【问题描述】:

我有一个给定的图像。我想在此图像上创建一个黑色条带作为叠加层,并在该条带上写上文字。 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

【问题讨论】:

    标签: python python-imaging-library pillow


    【解决方案1】:

    问题在于offsetdocs Image.paste 说:

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

    因此,使用(img_width/2, img_height/2),您将粘贴条带,其左上角位于大图像的中间。这里将“foo bar”粘贴到您的示例图片上:

    如果您将其更改为offset = (0, img_height/2),它将从左侧粘贴到一半下方。这是粘贴到正确位置的“foo bar”:

    条带可以稍微高一点(高度可以根据给定字体大小的文本计算),并且文本可以居中,但我希望这些事情已经在 Stack Overflow 或枕头文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多