【发布时间】: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