0

I want to display an image which is retrieved from mysql database display on webpage. I have used the following code. It displays the image in the screen, but not on the webpage.

Here is my code, which i have used.

    import mysql.connector
    import sys
    from PIL import Image
    import base64
    import six
    import io
    import PIL.Image
    import pymysql

    from flask import Flask,render_template,request,flash
    app=Flask(__name__)
    app.secret_key = 'dont tell anyone'

    @app.route('/')
    def index():
        db = mysql.connector.connect(user='root', password='tejA@1612',
                                      host='localhost',
                                      database='students')
        #photo = request.form['inputFile']
        image = Image.open('statics/rohan2.jpg')
        blob_value = open('statics/rohan2.jpg', 'rb').read()
        sql = 'INSERT INTO images(photo) VALUES(%s)'
        args = (blob_value, )
        cursor=db.cursor()
        cursor.execute(sql,args)
        sql1='select photo from images'
        db.commit()
        cursor.execute(sql1)
        data=cursor.fetchall()
        #print type(data[0][0])
        file_like=io.BytesIO(data[0][0])
        img=PIL.Image.open(file_like)
        #img.show()
        db.close()
        return render_template("home.html",result=img)
    if __name__=="__main__":
        app.run(debug=True)

Here is my home.html

<DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>This is Home page</h2>
<!--
  <form action="/projects/five" method="POST" enctype="multipart/form-data">
  <input type="file" name="inputFile"/>
    <input type="submit" class="btn btn-primary" name="button" value="Show All"/>
  </form>
-->
    {{ img }}
  </body>
</html>

Can anyone brief me on how to display this image on the webpage. and how to retrieve multiple images from mysql database and display on the webpage in grid style

1
  • Really, you should serve it as a static file... but as an alternative closer to what you have, you can look into doing base-64 encoding. Commented Jan 17, 2018 at 5:52

1 Answer 1

3
import base64
with open(path,"rb") as i:
    encoded_string = base64.b64encode(i.read())

Here, path is the path to the image.

Send this encoded string as response to the webpage.

<img  src="data:image/jpeg;base64;+encoded_string">

The above mentioned is the html code for displaying image send from python-flask as base64 encoding.

If you have any trouble do let me know.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.