Why is the captured image only saving as a blank image when trying to encode and store it in a database from a canvas?
Take a look at the following code snippet:
const player = document.getElementById('player');
const docs = document.getElementById('document')
const captureButton = document.getElementById('capture');
const constraints = {
video: true,
};
captureButton.addEventListener('click', (e) => {
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const imgFormat = canvas.toDataURL();
docs.value = imgFormat
context.drawImage(player, 0, 0, canvas.width, canvas.height);
e.preventDefault();
});
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
player.srcObject = stream;
});
<form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %}
<input type="text" name="documents" id="document">
<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width=320 height=240></canvas>
<button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button>
</form>
Also, here are the models and views.py associated with the code:
class Document(models.Model):
booking =models.ForeignKey(Booking,on_delete=models.PROTECT)
docs = models.ImageField(upload_to=upload_docs)
views.py:
import base64
from django.core.files.base import ContentFile
@login_required
def add_new_image(request,id):
obj = get_object_or_404(Booking,id=id)
if request.method == 'POST':
data = request.POST.get('documents')
format, imgstr = data.split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
if data:
photo = Document.objects.create(
booking = obj,
docs = data
)
photo.save()
return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no}))
else:
messages.error(request,_('choose or capture right image ..'))
return render(request,'booking/add_img.html',{'obj':obj,'form':images})
Any insights on why the captured image saves as blank would be greatly appreciated. Thank you.