簡體   English   中英

使用PIL / Pillow將疊加層(帶有文本)粘貼到基本圖像的頂部

[英]Pasting an overlay (with text) on top of a base image, using PIL/Pillow

我有給定的圖像。 我想在該圖像上創建一個黑色條作為覆蓋層,並在該條上寫入文字。 是我的意思的直觀示例。

我正在使用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

問題在於offset 文檔 Image.paste說:

如果改為使用2元組,則將其視為左上角。

因此,使用(img_width/2, img_height/2) ,您要粘貼帶有大圖像中間左上角的條。 這是將“ foo bar”粘貼到您的示例圖片上:

帶有原始代碼

如果將其更改為offset = (0, img_height/2) ,則會將其粘貼到一半但從左開始的位置。 這是粘貼到正確位置的“ foo bar”:

具有新的偏移

該條帶可以高一點(可以從給定字體大小的文本中計算出高度),並且可以將文本居中,但是我希望這些東西已經在Stack Overflow或Pillow文檔中的其他地方得到了解答。 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM