通过Ajax将画布图像数据(Uint8ClampedArray)发送到Flask Server [英] Send canvas image data (Uint8ClampedArray) to Flask Server via Ajax

查看:409
本文介绍了通过Ajax将画布图像数据(Uint8ClampedArray)发送到Flask Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过AJAX将HTML5上的图像数据发送到Flask服务器后端.我从使用context.getImageData(a, b, c, d)提取相关的图像数据,并且理想情况下希望在我的Flask后端以numpy数组的形式访问该数据.我最好怎么做?

I'd like to send image data on an HTML5 to a flask server back-end via AJAX. I extract the relevant image data from the using context.getImageData(a, b, c, d), and would ideally like to have access to that data as a numpy array on my flask backend. How might I best go about this?

谢谢!

推荐答案

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

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 ''

这篇关于通过Ajax将画布图像数据(Uint8ClampedArray)发送到Flask Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆