1 year ago

#383040

test-img

Anupam Chauhan

How to use pillow library to make image from letters in django?

When I try to draw images from the pillow library in django website hosted from pythonanywhere server it shows me an error with :

OSError at /confession
cannot open resource
Request Method: POST
Request URL:    https://luckyklyist.pythonanywhere.com/confession
Django Version: 4.0.3
Exception Type: OSError
Exception Value:    
cannot open resource
Exception Location: /home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/PIL/ImageFont.py, line 193, in __init__
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.9.5
Python Path:    
['/home/Luckyklyist/Confess/Confessout',
 '/var/www',
 '.',
 '',
 '/var/www',
 '/usr/local/lib/python39.zip',
 '/usr/local/lib/python3.9',
 '/usr/local/lib/python3.9/lib-dynload',
 '/home/Luckyklyist/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages']
Server time:    Wed, 06 Apr 2022 14:58:13 +0000

My code to work :

def confession(request):
    if request.method=="POST":
        message=request.POST.get('confession-msg')
        ide=random()
        # Drawing image
        img = Image.new('RGB', (1080, 1080), color=(0, 0, 0))
        d1 = ImageDraw.Draw(img)

        myFont = ImageFont.truetype("arial.ttf", size=40)
        words = message
        lines = textwrap.wrap(words, width=60)
        a = 0
        for word in lines:
            d1.text((0, a), word, fill=(255, 255, 255), font=myFont)
            a += 40
        img.save(f'{ide}.jpeg')
        imgge='{ide}.jpeg'
        confess=Confession(message=message,image=imgge)
        confess.save()
    dictionary={"message":message,"activehome":"active"}
    return render(request,"confession.html",dictionary)

But when i remove this part from the code it dosent show me error(OSError at /confession):

 # Drawing image
    img = Image.new('RGB', (1080, 1080), color=(0, 0, 0))
    d1 = ImageDraw.Draw(img)

    myFont = ImageFont.truetype("arial.ttf", size=40)
    words = message
    lines = textwrap.wrap(words, width=60)
    a = 0
    for word in lines:
        d1.text((0, a), word, fill=(255, 255, 255), font=myFont)
        a += 40
    img.save(f'{ide}.jpeg')

Models.py files

class Confession(models.Model):
    message=models.TextField()
    image=models.ImageField(upload_to="image")
    def __str__(self):
        return self.message

what should I do to make my web app create an image for me from which I store it in my pythoanywhere folder?

python

django

python-imaging-library

pythonanywhere

0 Answers

Your Answer

Accepted video resources