从烧瓶到本地脚本的base64图像

时间:2020-06-27 14:31:02

标签: vue.js flask base64 nativescript

我正在向Flask服务器发送请求,并希望服务器以base64映像作为响应,我试图在nativescript应用中显示此base64编码,但失败。

服务器代码

@app.route("/", methods=['POST', 'OPTIONS'])
def index():
    image = base64.b64decode(request.json.get('img'))
    image = np.array(Image.open(io.BytesIO(image)))
    print(image.shape)
    return base64.b64encode(image) # I know this returns the same image

客户端代码,我正在使用nativescript-vue

ImageSourceModule.ImageSource.fromAsset(this.src)
  .then(src => src.toBase64String("jpg"))
  .then(base64 => {
    return axios.post(
      "http://192.168.1.8:5000/",
      { img: base64 },
      {
        headers: { "Content-Type": "application/json" }
      }
    );
  })
  .then(res => {
    let img = ImageSourceModule.ImageSource.fromBase64Sync(res.data); // also tried the async version
    this.converted = img;
  })
  .catch(e => console.log(e));

在模板中

<Image :src="converted" ref="converted" margin="10" stretch="none" />

当我管理日志img时,它表示为空。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

找到解决方案,首先将numpy数组转换为PIL图像,然后将字节转换为base64字符串

input_image = base64.b64decode(request.json.get('img'))
input_array = np.array(Image.open(io.BytesIO(input_image)))
output_img = Image.fromarray(input_array, 'RGB')
buffer = io.BytesIO()
output_img.save(buffer, format="JPEG")
response = base64.b64encode(buffer.getvalue())