簡體   English   中英

將圖像從燒瓶放入 HTML5 畫布

[英]Putting an image from flask to an HTML5 Canvas

我正在嘗試在 HTML5 畫布上顯示在我的 python 后端生成的圖像。

我嘗試過的燒瓶代碼的兩種變體:

1)

@app.route(r'/api/a', methods=["GET", "POST"])
def send_heatmap():
           return open(r"..\\a\\b\\50.png", "rb").read()

2)

@app.route(r'/api/a', methods=["POST"])
def send_heatmap():
    img = io.BytesIO(open(r"..\\a\\b\\50.png", "rb").read())
    return send_file(img, mimetype='image/png', as_attachment=True, attachment_filename="heatmap.png")

不同的 JS 嘗試之一:

console.log(result);
var canvas = document.getElementsByTagName('canvas');
context = canvas[1].getContext('2d');
var a = new ImageData(result["content"], 480)
context.putImageData(a, 0, 0);

我的另一個 JS 嘗試從圖像中剝離了標題信息,但也沒有骰子。

我收到Uncaught DOMException: Failed to construct 'ImageData': The source width is zero or not a number. 除其他問題外。 我如何將數據從python發送到js?

通過這個最小的工作示例,我可以在畫布上看到圖像。

如果您訪問主頁http://localhost:5000/然后腳本將從http://localhost:5000/api/a加載圖像並在畫布上繪制。

from flask import Flask, send_file


app = Flask(__name__)


@app.route('/api/a')
def image():
    return send_file('/home/user/images/ball.png',  mimetype='image/png')


@app.route('/')
def index():
    return '''
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName('canvas');
var ctx = canvas[0].getContext('2d');

var img = new Image();
img.src = "/api/a";

// it can't draw it at once. it has to wait till image is loaded
//ctx.drawImage(img, 0, 0);

img.onload = function() {
   img.style.display = 'none'; // I don't know why they hide it 
   ctx.drawImage(img, 0, 0);   // draw on canvas
};
</script>
'''

app.run()

要將Image to轉換Image to ImageData, you have to draw it on畫布you have to draw it on

img.onload = function() {
  console.log('WxH: ' + img.width + 'x' + img.height)

  img.style.display = 'none';  // hide it

  ctx.drawImage(img, 0, 0);  // draw Image on canvas

  var imageData = ctx.getImageData(0, 0, img.width, img.height);  // get ImageData from canvas

  ctx.putImageData(imageData, 10, 10);  // put ImageData in differen place
};

我從使用畫布進行像素操作中獲取的有關畫布的信息


編輯:生成圖像並發送而不保存在磁盤上。

import numpy as np
from PIL import Image
import io

@app.route('/api/a')
def array():
    arr = np.array([
        [255, 255,   0,   0,   0,   0,   0,   0, 255, 255],
        [255,   0, 255, 255, 255, 255, 255, 255,   0, 255],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255, 255,   0, 255, 255,   0, 255, 255,   0],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255,   0, 255, 255, 255, 255,   0, 255,   0],
        [  0, 255, 255,   0,   0,   0,   0, 255, 255,   0],
        [255,   0, 255, 255, 255, 255, 255, 255,   0, 255],
        [255, 255,   0,   0,   0,   0,   0,   0, 255, 255],
    ])

    img = Image.fromarray(arr.astype('uint8')) # convert arr to image

    file_object = io.BytesIO()   # create file in memory 
    img.save(file_object, 'PNG') # save PNG in file in memory
    file_object.seek(0)          # move to beginning of file

    return send_file(file_object,  mimetype='image/png')

畫布上的圖像數據

完整代碼:

from flask import Flask, send_file

import numpy as np
from PIL import Image
import io


app = Flask(__name__)


@app.route('/')
def index():
    return '''
<!DOCTYPE html>
<html>
<body>
<canvas></canvas>
<script>
var canvas = document.getElementsByTagName('canvas');
var ctx = canvas[0].getContext('2d');

var img = new Image();
img.src = "/api/b";

// it can't draw it at once. it has to wait till it is loaded
//ctx.drawImage(img, 0, 0);

img.onload = function() {
  img.style.display = 'none'; // I don't know why they hide it

  console.log('WxH: ' + img.width + 'x' + img.height)

  // convert Image to ImageData
  //(it has to draw on canvas so it could need second canvas for this)

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

  //put ImageData many times  
  for(x = 0 ; x < 100 ; x += 10) {
    for(y = 0 ; y < 100 ; y += 10) {
       ctx.putImageData(imageData, x, y);
    }
  }
};
</script>
</body>
</html>
'''


@app.route('/api/b')
def array():
    '''
    generate image from numpy.array using PIL.Image
    and send without saving on disk using io.BytesIO'''

    arr = np.array([
        [255, 255,   0,   0,   0,   0,   0,   0, 255, 255],
        [255,   0, 255, 255, 255, 255, 255, 255,   0, 255],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255, 255,   0, 255, 255,   0, 255, 255,   0],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255, 255, 255, 255, 255, 255, 255, 255,   0],
        [  0, 255,   0, 255, 255, 255, 255,   0, 255,   0],
        [  0, 255, 255,   0,   0,   0,   0, 255, 255,   0],
        [255,   0, 255, 255, 255, 255, 255, 255,   0, 255],
        [255, 255,   0,   0,   0,   0,   0,   0, 255, 255],
    ])

    img = Image.fromarray(arr.astype('uint8')) # convert arr to image

    file_object = io.BytesIO()   # create file in memory 
    img.save(file_object, 'PNG') # save as PNG in file in memory
    file_object.seek(0)          # move to beginning of file
                                 # so send_file() will read data from beginning of file

    return send_file(file_object,  mimetype='image/png')


app.run()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM