Django项目使用PIL解码base64图片出现padding错误如何解决
你遇到的binascii.Error: Incorrect padding报错是由于base64编码规则要求字符串长度必须为4的整数倍,不足时需要用=补位,同时你的前后端传参逻辑、后端代码也存在其他错误,修复步骤如下:
- 修复前端传参逻辑
你当前直接把base64字符串作为POST请求的整个请求体传递,后端只能把base64内容当作表单键解析,逻辑极不稳定。修改前端predict按钮的点击事件,将base64放入指定键值对传递:
$("#predict-button").click(function(event){ let message = base64Image; console.log(message); // 修改post传递格式,用键值对传参 $.post("{% url "diagnose:submit_prediction" %}", {image_base64: message}, function(response){ $("#covid-prediction").text(response.prediction.covid.toFixed(3) * 100 + "%"); $("#health-prediction").text(response.prediction.health.toFixed(3) * 100 + "%"); console.log(response); }); });
如果需要兼容所有图片格式,还可以把base64前缀的替换逻辑改成通用正则匹配,避免png、webp等格式无法正确去除前缀:
base64Image = dataURL.replace(/^data:image\/[^;]+;base64,/, "");
- 修复后端逻辑
首先补全base64的补位符,同时修正原有代码的变量错误、返回值错误(Django没有jsonify方法,该方法属于Flask,Django需要用JsonResponse),修改后代码如下:
import base64 import io from PIL import Image from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def predict_chances(request): if request.method != "POST": return JsonResponse({"error": "仅支持POST请求"}, status=400) # 直接取前端传递的base64参数,不需要遍历POST字典 encoded = request.POST.get("image_base64", "").strip() if not encoded: return JsonResponse({"error": "未收到图片数据"}, status=400) # 补全base64 padding,解决padding错误 missing_padding = 4 - len(encoded) % 4 if missing_padding: encoded += '=' * missing_padding # 解码生成图片对象 im = Image.open(io.BytesIO(base64.b64decode(encoded))) # 修正原代码的变量错误:原代码使用了未定义的image变量,替换为im processed_image = preprocess_image(im, target_size=(224, 224)) prediction = model.predict(processed_image).tolist() response = { 'prediction': { 'covid': prediction[0][0], 'health': prediction[0][1] } } # 用Django自带的JsonResponse返回 return JsonResponse(response)
以上修改完成后即可解决padding报错,同时其他隐藏的逻辑错误也会一并修复。
内容的提问来源于stack exchange,提问作者nujabesss
相关产品推荐
相关产品推荐

