0

So I am working on a project and I want to render images I have stored inside my MySQL database. I created the tables using MySQLAlchemy and I am basically doing everything related to the db with that. Here is my code:

class Post1(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title=db.Column(db.String(120), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    img = db.Column(db.BLOB(800000), nullable=False)
    mimetype = db.Column(db.String(10))
@app.route('/read')
def read():
    img = Post1.query.filter_by(id=Post1.id).first()
    return render_template('readmanga.html', img=img.img)
<html>
    <head>

    </head>
    <body>
        <div><img src="" alt="" class="page"></div>
    </body>
</html>

So here is what I want to do. I want to be able to render the image I stored in the img column in the Post1 class in the tag with the class="page" in the given template. I have absolutely no clue how to do this so please help me.

Addy
  • 19
  • 3

1 Answers1

0

You are retrieving an image as a blob, so you can't use the image value directly in the 'src' attribute from the tag , therefore, before you'd need to convert to some base64 image:

import base64
@app.route('/read')
def read():        
    img = Post1.query.filter_by(id=Post1.id).first()
    encoded_image = base64.b64encode(img.img)
    return render_template('readmanga.html', img=encoded_image )

Then you can consume it in your template using interpolation '{{ img }}'

<html>
    <head>

    </head>
    <body>
        <div><img src="data:image/png;base64,{{ img }}" alt="" class="page"></div>
    </body>
</html>
Bruno
  • 924
  • 9
  • 20
  • I did do that but I am not getting the image I have in my database. Rather, it is just showing me an image icon. When I inspected the element, it said, "value too large to edit" when I clicked on the src tag. How can I fix this? – Addy Jun 10 '22 at 20:52
  • @Addy can you inform which type is your img? I'm suspecting it's a string, therefore you'd need to convert to byte array first before using the base64.b64encode() function – Bruno Jun 10 '22 at 21:21
  • it is a string (I think) because in the database, it really is just a bunch of random characters. – Addy Jun 10 '22 at 21:43