Python implementation of flash in the return of image stream to the front-end display

Time:2021-4-26

Scenario requirements:You need to find a picture in the local flash server and return it to the front end for display.

Questions:Usually, the front-end < img > tag will only accept the form of URL to display the image, and never try to return a local image of the server to the front-end.

So write a record of this scene that seems a little strange. (usually, personal blogs, personal websites have no money, and third-party services will be stored locally on the server.)

Project directory:

dyy_project

|

|—-Static (created automatically when creating a new flash project, without any files)

|—-templates

|—– index.html (front page)

|—-dyy_ project.py (flash project startup file)

File content: dyy_ project.py

#!/usr/bin/env python
# coding=utf-8
 
from flask import Flask
from flask import render_template
 
app = Flask(__name__)
 
"""
This is an example of how flash reads the local image of the server and returns the image stream to the front-end display
"""
 
 
def return_img_stream(img_local_path):
  """
  Tool function:
  Get local image stream
  :param img_ local_ Path: the local absolute path of a single image in a file
  : Return: image stream
  """
  import base64
  img_stream = ''
  with open(img_local_path, 'r') as img_f:
    img_stream = img_f.read()
    img_stream = base64.b64encode(img_stream)
  return img_stream
 
 
@app.route('/')
def hello_world():
  img_path = '/home/hogan/Googlelogo.png'
  img_stream = return_img_stream(img_path)
  return render_template('index.html',
              img_stream=img_stream)
 
 
if __name__ == '__main__':
  app.run(debug=True, port=8080)

Contents of the document: index.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Flask Show Image</title>
</head>
<body>
  <img style="width:180px" src="data:;base64,{{ img_stream }}">
</body>
</html>

be careful:The Src in the IMG tag must follow the data:; base64,{{img_ Stream}, otherwise the image will not be displayed.

Then start your flag program and visit http://127.0.0.1 You can see your picture.

The above Python implementation of flash returns the image stream to the front-end display, which is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developer more.

Recommended Today

Front end interview daily 3 + 1 – day 662

Today’s knowledge points (2021.02.07) – day 662(I want to write a question, too) [html] What do you think is the most difficult part of developing a new website? [css] Please draw a dotted line with pure CSS and set the gap between the dotted lines (pictures are not allowed) [js] How does the clipboard in […]