You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Base64传输图片至Flask后端,PIL无法识别图片报错求助

问题原因

你前端的Base64编码逻辑完全错误——你把图片URL字符串用btoa编码了,而不是图片的实际二进制内容。后端解码后得到的是"URL="../static/images/images_final.jpg""这个字符串的字节,根本不是有效的图片文件,所以Pillow识别失败。

修正方案

前端JavaScript代码修改

需要先获取图片的二进制数据,再转换为Base64。如果是加载服务器上的静态图片,可以用fetch获取图片资源后转码:

async function handleImage (){
  // 获取图片资源
  const response = await fetch("../static/images/images_final.jpg");
  const blob = await response.blob();
  // 将Blob转为Base64
  const reader = new FileReader();
  reader.onload = function() {
    // 取出Base64字符串(注意去掉前缀"data:image/jpeg;base64,")
    const base64Image = reader.result.split(',')[1];
    // 发送POST请求
    fetch("/predict", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ image: base64Image })
    })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
  };
  reader.readAsDataURL(blob);
}

后端Flask代码调整

确保解码后的字节流正确,另外注意返回结果的格式(TensorFlow模型的predict结果通常需要转为可序列化的格式):

import io
import base64
from PIL import Image
from flask import request, jsonify

@app.post("/predict")
def predict_image():
    req = request.get_json(force=True)
    b64Image = req["image"]
    
    try:
        buf = base64.b64decode(b64Image)
        image = Image.open(io.BytesIO(buf))
        # 如果模型需要特定格式(比如RGB),可以转换
        image = image.convert("RGB")
        # 运行预测并转为可JSON序列化的格式
        prediction = TF_MODEL.predict(image).tolist()
        return jsonify({"prediction": prediction})
    except Exception as e:
        return jsonify({"error": str(e)}), 400
关键注意点
  • 前端转Base64时,readAsDataURL会生成带前缀的字符串,必须去掉前缀才能让后端正确解码。
  • 确保图片格式和模型要求一致(比如是否需要RGB、特定尺寸等),必要时在后端对图片进行预处理。

内容的提问来源于stack exchange,提问作者Louis Lecouturier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:51:17