this is probably the only interesting flask code:
@app.route("/index.html", methods=["GET", "POST"])
def index():
if request.method == "POST":
user_input = request.form.get("user_input")
return render_template("image.html", user_input=user_input)
else:
return render_template("index.html")
@app.route("/generate_image/<string:user_string>")
def generate_image(user_string):
#select one of the example images
num = randint(1, 8)
image = Image.open(f"./pics/{num}.jpeg")
# Create a new response object and set the content type to "image/png"
response = make_response(image.tobytes())
response.headers.set('Content-Type', 'image/jpeg')
# Return the response to the user
return response
the image.html file contains this:
<img src={{ url_for('generate_image', user_string=user_input) }}>
getting this in the terminal:
127.0.0.1 - - [24/Apr/2023 21:49:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:10] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:10] "GET /static/favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "POST /index.html HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /static/styles.css HTTP/1.1" 200 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /static/favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [24/Apr/2023 21:49:13] "GET /generate_image/thing HTTP/1.1" 200 -
the folders are correctly organized, with the "pics" folder being in the same directory as the python file. Any ideas what is going wrong?
I've tried parsing this through several debugger ais but all have come up empty handed...
By setting the Content-Type
to image/jpeg
you have told the browser to expect a compressed, JPEG-encoded image with a width, a height, possibly a copyright, possibly some EXIF and GPS data.
But actually you have decoded and decompressed your JPEG with Image.open()
and then converted it to bytes
so you are in fact sending the first pixel, then the second pixel with no header and no compression.
You just need to send the binary contents of the JPEG:
with open('image.jpg', 'rb') as fd:
JPEG = fd.read()
You don't even need PIL
because you aren't interested in interpreting or understanding the image, you just want to send its contents.