'Using Python Flask, display images on webpage from mysql database
I have created web based app using python flask for collecting students info.
I have created a 'students' database in which I am collecting students profile including their photo by creating 'images' table For 'photo' filed, I am using BLOB data type in mysql.
Here is my code:
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 display_image():
db = mysql.connector.connect(user='root', password='######',
host='localhost',
database='students')
cursor=db.cursor()
sql1='select photo from images'
cursor.execute(sql1)
#db.commit()
data=cursor.fetchall()
#print type(data[0][0])
file_like=io.BytesIO(data[0][0])
img=PIL.Image.open(file_like)
db.close()
return render_template("home.html",data=file_like)
if __name__=="__main__":
app.run(debug=True)
I want to render the image to html file and want to display on web page Here is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2>This is my file upload page</h2>
<table>
{% for item in data %}
<tr>
<td>{{item[0]}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
The result on the webpage is as follows:
I want to display image itself on the webpage, but it is displaying in binary mode.
Can you pls brief me to fix this issue or suggest any article that help me to retrieve images from mysql using python flask and display on web page or can you provide me the code if possible.
Thanking you With regards, Ramesh V
Solution 1:[1]
You are passing a stream to your template, rather than an image.
Python encoding, assumes that I/O will write to .jpg:
import base64
imgdata = base64.b64decode(file_like)
filename = 'some_image.jpg' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
from @rmunn response here: How to convert base64 string to image?
Would be a good idea to store extension in your database with your images, so that you know how to encode them properly on exit. Would be even better to implement a content management system, where your files are available via url, and then to store those urls in your db. More work up front, but keeps streams out of your database and in a filesystem as files, where they belong.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John R |