diff --git a/API/main.py b/API/main.py index 1e8d3ea..82c2549 100755 --- a/API/main.py +++ b/API/main.py @@ -1,6 +1,8 @@ #!/usr/bin/env python from deps.samplebase import SampleBase from rgbmatrix import graphics +from PIL import Image +import requests from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin @@ -11,6 +13,58 @@ import time, threading api = Flask(__name__) cors = CORS(api) +@api.route('/text', methods=['POST']) +@cross_origin() +def set_image(): + # prepare response data + response = { 'success': True } + try: + global matrix + assert matrix is not None + + # receive client data + data = request.form + # try unpacking text and x,y coordinates + url = data.get('url') + + # call matrix method with data + matrix.set_image(url) + except Exception as e: + # error handling + print(e) + response['success'] = False + + # respond to client + return jsonify(response) + +@api.route('/text', methods=['POST']) +@cross_origin() +def display_image(): + # prepare response data + response = { 'success': True } + try: + global matrix + assert matrix is not None + + # receive client data + data = request.form + # try unpacking image width and height + width = int(data.get('w')) + height = int(data.get('h')) + # try unpacking x,y coordinates + x_coord = int(data.get('x')) + y_coord = int(data.get('y')) + + # call matrix method with data + matrix.display_image(x_coord, y_coord, width, height) + except Exception as e: + # error handling + print(e) + response['success'] = False + + # respond to client + return jsonify(response) + @api.route('/text', methods=['POST']) @cross_origin() def display_text(): @@ -191,6 +245,8 @@ class Matrix(SampleBase): self.font.LoadFont("deps/fonts/9x18B.bdf") # initialize color self.color = graphics.Color(255, 255, 255) + # initialize image + self.image = None # initialize canvas self.canvas = self.matrix.CreateFrameCanvas() @@ -233,6 +289,17 @@ class Matrix(SampleBase): # set next pixel in rectangle self.canvas.SetPixel(x+i, y+j, self.color.red, self.color.green, self.color.blue) + # set current image + def set_image(self, url: str): + self.image = Image.open(requests.get(url, stream=True).raw) + + # display rectangle at position with dimensions in current color + def display_image(self, x: int, y: int, w: int|None = None, h: int|None = None): + # resize image to specified or max size + self.image.resize((w or self.matrix.width, h or self.matrix.height), Image.ANTIALIAS) + # set image at position + self.canvas.SetImage(self.image, x, y) + # initialize global matrix variable matrix = None