S
S
Shato Daltsaev2019-03-13 01:42:54
Python
Shato Daltsaev, 2019-03-13 01:42:54

How to solve the problem with putting text on an image in Flask?

I can't figure it out, I'm doing everything right.
There is a page with an input, text is entered into the input and the send button is pressed

@application.route('/result',methods = ['POST', 'GET'])
    def result():
       if request.method == 'POST':
          if request.form.get("serial_number") != "":
             set_serial_number(request.form.get("serial_number"))
       save_image()
       path = "sts_new.png"
       return send_file(path, as_attachment=True)

the method catches everything fine, then I need to put this text on the image.
image = Image.open('sts.png').convert("RGBA")
size = 1413, 1000
txt = Image.new('RGBA', size, (255,255,255,0))
draw = ImageDraw.Draw(txt)

    def set_serial_number(serial_number):
        (x, y) = (900, 50)
        message = serial_number
        font_serial = ImageFont.truetype('2057.ttf', size=43)
        draw.text((x, y), message, fill=(200, 0, 0, 255), font=font_serial)

Then saved..
def save_image():
        combined = Image.alpha_composite(image, txt)
        combined.save('sts_new.png')

Everything is great. Everything is working. then I refresh the page and enter the text again, press the submit button and get the overlay of the previous entered text with the new one. something like that. enter image description here
I can't figure out where it gets the previous image from? sts_new.png - the file was deleted even when the page was updated, but it still keeps it somewhere. How can I solve this problem?
link to gist https://gist.github.com/Shatoidil/22a4d5d851352653...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-03-13
@Shatoidil

And so?

with Image.open('sts.png').convert("RGBA") as your_image:
    do_things(your_image)

UPD: rewrote your code, try this
def draw_text_on_image(text,
                       input_file='image.png',
                       output_file='new_image.png',
                       dimensions=(1047, 377),
                       insert_position=(900, 50),
                       ):

    with Image.open(input_file).convert("RGBA") as your_image:
        temporary_image = Image.new('RGBA', dimensions, (255, 255, 255, 0))
        draw = ImageDraw.Draw(temporary_image)

        draw.text(insert_position, text, fill=(200, 0, 0, 255))
        del draw
        output = Image.alpha_composite(your_image, temporary_image)
        output.save(output_file)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question