Skip to content

Instantly share code, notes, and snippets.

@nitred
Last active April 12, 2018 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitred/b659c856b971d9d2179dd53b30d0b5b6 to your computer and use it in GitHub Desktop.
Save nitred/b659c856b971d9d2179dd53b30d0b5b6 to your computer and use it in GitHub Desktop.
Web Utils

About

Utility function and snippets for the web

Table of Contents

  • Flask PNG snippet
  • Simple drawingboard

Source

Prerequisites

Download the following files and serve them in a static folder.

Simple Drawingboard HTML

<html>
<head>
    <link type="text/css" rel="stylesheet" href="static/drawingboard.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
    <script type="text/javascript" src="static/drawingboard.js"></script>
</head>

<body>

    <div align="center">
        <h1>Simple DrawingBoard!</h1>
    </div>

    <div align="center">
        <div id="simple-board"></div>
    </div>

    <style>
    	#simple-board {
    		width: 800px;
    		height: 400px;
    	}
    </style>
    <script>
        $(document).ready(function() {
            var simpleBoard = new DrawingBoard.Board('simple-board', {
                controls: false,
                webStorage: false
            });
        });
    </script>

</body>
</html>

Server.py

"""Taken parially from: https://gist.github.com/wilsaj/862153"""
import base64
from flask import Flask, make_response, render_template

app = Flask(__name__)

# DO OTHER STUFF HERE ...


@app.route('/png_page', methods=['GET'])
def png_page():
    """Endpoint that renders and HTML page that requests for a png image."""
    return render_template('png-page.html')


@app.route('/get_png', methods=['GET'])
def get_png():
    """Endpoint that returns PNG Image as byte64 bytestring."""
    filename = 'path/to/image.png'
    with open(filename, "rb") as image_file:
        encoded_bytes = base64.b64encode(image_file.read())

    response = make_response(encoded_bytes)
    response.headers['Content-Type'] = 'image/png'
    return response

png-page.html

<!-- Author: Maxim Maltsev (https://github.com/mmaltsev) --> 
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
  
<body>
    <div align="center">
        <img src="" id="resultImage" />
    </div>

    <script>
        $(document).ready(function() {
            $.get("{{ url_for('get_png') }}", function(data) {
                $('#resultImage').attr('src', 'data:image/png;base64,' + data);
                console.log( "Load was performed." );
            });
        });
    </script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment