Insert overlay (with text) over the base image using PIL / Pillow

I have an image. I want to create a black stripe as an overlay on this image, with text written on the specified stripe. Here is a visual example of what I mean.

I am using Python PILto accomplish this (in a Django project), and here is what I have written so far:

from PIL import Image, ImageFont, ImageDraw

img_width, img_height = img.size #getting the base image 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.

This does not work at all. As in the case, the image appears without text or a black bar, as it was originally.

Please note that if I'm directly trying to write on an image (without a black bar), it works fine. Moreover, image processing itself works fine (i.e., in those cases when I do not write anything on the image).

- ? - ( )? ? RGB ? ? . Btw ; , .


, , :

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
+4
1

offset. docs Image.paste :

2-, .

, (img_width/2, img_height/2) . "foo bar" :

With source code

offset = (0, img_height/2), , . "foo bar" :

With a new offset

( ), , , .

+1

Source: https://habr.com/ru/post/1676012/


All Articles