![](/img/trans.png)
[英]How do I center my text on an image using PIL in python and save the image with a different name in a for or while loop?
[英]By Using python pil, I want to make image centered with text from url and download. How to do it?
我在url中輸入了文本,並希望獲得文本居中的下載圖像。
例如,當我輸入http://127.0.0.1:8000/app/hello時 ,便會下載圖像。 該圖像使文本“ hello”居中
def homework(request, name):
text = name
img = Image.new('RGB',(256,256),(0,0,0))
draw = ImageDraw.Draw(img)
font = ImageFont.load_default().font
draw.text((128,128), text, font = font, fill="black")
with open(img, 'rb') as f:
response = HttpResponse(f, content_type='image/jpeg')
response['Content-Disposition'] = 'attachment; filename="textimage"'
return response
通過使用python pil。
怎么做?
#install PIL (Pillow) via Pip
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
#position of Text
x = 50
y = 50
#font color as tuple
color = (255, 255, 255)
#download the image to the local system and open it
img = Image.open("1.jpg")
#draw image and prepare font
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('arial.ttf', size=30)
#draw text on image
draw.text((x, y),"Sample Text", color,font=font)
#save the new image, that contains the text
img.save('sample-out.jpg')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.