从 flask 到 nativescript 的 base64 图像

base64 image from flask to nativescript

我正在向 Flask 服务器发送请求并期望服务器响应 base64 图像,我试图在 nativescript 应用程序中显示此 base64 编码但失败了。

server code

@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

client code, I am using 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));

in the template

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

当我控制日志 img 时,它说 null。有什么想法吗?

找到解决方案,numpy数组需要先转成PIL Image然后bytes再转成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())