且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过Ajax将画布图像数据(Uint8ClampedArray)发送到Flask Server

更新时间:2023-11-27 15:04:10

一种成功的(尽管可能不是***效率的)方法来解决

A successful (although perhaps not optimally efficient) method for dealing with this is to

  1. 将imageData放到画布(context.putImageData)
  2. 从此canavs(canvas.toDataURL)创建数据URL
  3. 将此数据URL作为base64发送到服务器
  4. 在python端进行一些转换工作,使其变为numpy形状
  1. Put the imageData onto a canvas (context.putImageData)
  2. Create a data URL from this canavs (canvas.toDataURL)
  3. Send this data URL to the server as base64
  4. Do some conversion work on the python side to get it into numpy shape

客户端(JS)

var scratchCanvas = document.createElement('canvas');
var context = scratchCanvas.getContext('2d');
context.putImageData(...);
var dataURL = scratchCanvas.toDataURL();
$.ajax({
  type: "POST",
  url: "http://url/hook",
  data:{
    imageBase64: dataURL
  }
}).done(function() {
  console.log('sent');
});

服务器端(Python/Flask)

# ... Flask imports above ...
import numpy as np
from PIL import Image
import base64
import re
import cStringIO

@app.route('/hook', methods=['POST'])
def get_image():
    image_b64 = request.values['imageBase64']
    image_data = re.sub('^data:image/.+;base64,', '', image_b64).decode('base64')
    image_PIL = Image.open(cStringIO.StringIO(image_b64))
    image_np = np.array(image_PIL)
    print 'Image received: {}'.format(image_np.shape)
    return ''