Vegoti Ramesh
Vegoti Ramesh

Reputation: 9

how to display image on webpage using python

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

Upvotes: 0

Views: 5949

Answers (1)

Athul Soori
Athul Soori

Reputation: 91

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.

Upvotes: 3

Related Questions