I've some trouble with decode base64 image in my django project.
I am passing the image to views like this (I've some form. I'm passing image to function from views.py through this form):
{% extends "blog/base.html" %}
{% block content %}
<div id="content" class="container-fluid d-flex h-100 justify-content-center align-items-center p-0">
<div class="row bg-white shadow-sm">
<div class="col border rounded p-4">
<h3 class="text-center mb-4">Диагноз</h3>
<form action="" id="post-form">
<div class="form-group">
<p align="center" style="font-weight:bold"><label for="exampleFormControlFile1">Снимок</label></p>
<input type="file" class="form-control-file" id="image-selector">
</div>
</form>
<p align="center" style="font-weight:bold">Predictions</p>
<p>Covid: <span id="covid-prediction"></span></p>
<p>Health: <span id="health-prediction"></span></p>
<table align="center">
<tr>
<td>
<img id="selected-image" class="img-thumbnail" width="300px" height="300px" src=""/>
</td>
</tr>
<tr align="center">
<td>
<button id="predict-button" type="submit" class="btn btn-primary">Predict</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
let base64Image;
$("#image-selector").change(function() {
let reader = new FileReader();
reader.onload = function(e) {
let dataURL = reader.result;
$("#selected-image").attr("src", dataURL);
base64Image = dataURL.replace("data:image/jpeg;base64,","");
console.log(base64Image);
}
reader.readAsDataURL($("#image-selector")[0].files[0]);
$("#covid-prediction").text("");
$("#health-prediction").text("");
});
$("#predict-button").click(function(event){
let message = base64Image;
console.log(message);
$.post("{% url "diagnose:submit_prediction" %}", message, function(response){
$("#covid-prediction").text(response.prediction.covid.toFixed(3) * 100 + "%");
$("#health-prediction").text(response.prediction.health.toFixed(3) * 100 + "%");
console.log(response);
});
});
</script>
And in my views file I'm trying to decode this image like this:
@csrf_exempt
def predict_chances(request):
myDict = request.POST.dict()
encoded = 0
for k in myDict:
encoded = k
print(encoded)
im = Image.open(io.BytesIO(base64.b64decode(encoded)))
processed_image = preprocess_image(image, target_size=(224, 224))
prediction = model.predict(processed_image).tolist()
response = {
'prediction': {
'covid': prediction[0][0],
'health': prediction[0][1]
}
}
return jsonify(response)
But this is not working. I get this error:
binascii.Error: Incorrect padding
How I can fix this?