Return the image data with Flask of Python and draw it to the canvas element of HTML

The image data acquired by Flask of Python is drawn on the canvas element of HTML.

Thing you want to do

Read the image data saved in Google Cloud Storage with Cloud functions and draw it on the canvas element of your HTML. In Cloud functions, the image is first read in blob format. Convert this to png or jpg, return it with flask, and draw it with the canvas element.

Load and download Storage files with Cloud functions

I didn't hesitate because the official documents are extensive here.

https://cloud.google.com/storage/docs/downloading-objects#code-samples

main.py


from google.cloud import storage

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    #bucket_name is the name of the storage destination created in Storage. Manually set
    
    blob = bucket.blob(source_blob_name)#In short, the file name
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

When executed, the file will be downloaded locally.

Instead of downloading as a single file, return as jpg with flask and download

It started to get stuck around here. In short, read the blob in bytes, add header etc. to it and return it as an image. At that time, use Flask's send_file module. No, you don't know this.

In addition, since hosting is done by Cloud functions of GCP this time, there is no app.run () etc. However, if you host this, the download_blob () function will work if you hit a certain URL.

main.py


from google.cloud import storage
import io
from flask import send_file

def download_blob(request):
    """Downloads a blob from the bucket."""
    bucket_name = "your-bucket-name"
    source_blob_name = "storage-object-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    #bucket_name is the name of the storage destination created in Storage. Manually set
    
    blob = bucket.blob(source_blob_name)#In short, the file name
    image_binary= blob.download_as_bytes()
    return send_file(
            io.BytesIO(image_binary),
            mimetype='image/jpeg',
            as_attachment=True,
            attachment_filename='%s.jpg' % source_blob_name)

Refer to the following for deployment with Cloud functions. https://qiita.com/NP_Systems/items/f0f6de899a84431685ff

If you have installed the library etc., just type the following to emulate it locally.

teriminal.


functions-framework --target=hello  --port=8081

Hit the hosted URL and the image will be downloaded. But unlike a single file, it is returning. Use this to draw what you receive on the canvas

Depiction on canvas element

This is also quite clogged. Even though it's such a simple thing. This site was really helpful. https://stackoverflow.com/questions/57014217/putting-an-image-from-flask-to-an-html5-canvas

It's php, but html is similar.

index.php


<?php get_header(); ?>
<main>
<article>
  <section>
       <input type="button" value="Start" onclick="main();"/>
        <canvas></canvas>
  </section>
</article>
</main>

<script language="javascript" type="text/javascript">

    function main(){
      var canvas = document.getElementsByTagName('canvas');
      var ctx = canvas[0].getContext('2d');

      var img = new Image();
      img.src = 'http://0.0.0.0:8081';//URL hosted on Flask

      img.onload = function() {
        img.style.display = 'none'; //I don't know
        console.log('WxH: ' + img.width + 'x' + img.height)

        ctx.drawImage(img, 0, 0);
        var imageData = ctx.getImageData(0, 0, img.width*2, img.height*2)

        for(x = 0 ; x < 100 ; x += 10) {
          for(y = 0 ; y < 100 ; y += 10) {
             ctx.putImageData(imageData, x, y);
          }
        }
      };    }
</script>
<?php get_footer(); ?>

Impressions

No, it was such a simple thing, but I got stuck. I feel that I have little understanding of blobs and pngs.

Recommended Posts

Return the image data with Flask of Python and draw it to the canvas element of HTML
Try to image the elevation data of the Geographical Survey Institute with Python
POST the image with json and receive it with flask
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
I tried to find the entropy of the image with python
Output the contents of ~ .xlsx in the folder to HTML with Python
Convert the result of python optparse to dict and utilize it
HTML email with image to send with python
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
Send and receive image data as JSON over the network with Python
[python] Send the image captured from the webcam to the server and save it
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I tried to get and analyze the statistical data of the new corona with Python: Data of Johns Hopkins University
The story of making a tool to load an image with Python ⇒ save it as another name
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
[Note] Export the html of the site with python.
[Introduction to Python] How to get the index of data with a for statement
(Diary 1) How to create, reference, and register data in the SQL database of Microsoft Azure service with python
Extract the table of image files with OneDrive & Python
How to scrape image data from flickr with python
Visualize the range of interpolation and extrapolation with python
Convert the image in .zip to PDF with Python
Extract the band information of raster data with python
[Python Data Frame] When the value is empty, fill it with the value of another column.
Build API server for checking the operation of front implementation with python3 and Flask
How to identify the element with the smallest number of characters in a Python list?
Extract images and tables from pdf with python to reduce the burden of reporting
I tried to automate the article update of Livedoor blog with Python and selenium.
[Note] How to write QR code and description in the same image with python
It was a little difficult to do flask with the docker version of nginx-unit
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
I just wanted to extract the data of the desired date and time with Django
How to count the number of occurrences of each element in the list in Python with weight
I tried to compare the processing speed with dplyr of R and pandas of Python
It is easy to execute SQL with Python and output the result in Excel
Try scraping the data of COVID-19 in Tokyo with Python
I tried "gamma correction" of the image with Python + OpenCV
[Python environment maintenance] De-NeoBundle. Prepare the environment of the super convenient complementary plug-in jedi-vim with dein and set it to be comfortable
How to interactively draw a machine learning pipeline with scikit-learn and save it in HTML
[pyqtgraph] Add region to the graph and link it with the graph region
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
Python application: Data cleansing # 3: Use of OpenCV and preprocessing of image data
Recursively get the Excel list in a specific folder with python and write it to Excel.
Get rid of dirty data with Python and regular expressions
Solve the spiral book (algorithm and data structure) with python!
The story of rubyist struggling with python :: Dict data with pycall
[Homology] Count the number of holes in data with Python
Build a Python environment and transfer data to the server
Try to automate the operation of network devices with Python
[Let's play with Python] Image processing to monochrome and dots
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
I made a function to crop the image of python openCV, so please use it.
[Introduction to Data Scientists] Basics of Python ♬ Functions and classes
The process of making Python code object-oriented and improving it
I want to know the features of Python and pip
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
Get additional data to LDAP with python (Writer and Reader)
Play with the password mechanism of GitHub Webhook and Python