0

im trying to save captured image ( encoding data) into database from canvas , but it only saves a blank image ?

here is my code

    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>

and here is my views.py with models.py

class Document(models.Model):
    booking =models.ForeignKey(Booking,on_delete=models.PROTECT)
    docs = models.ImageField(upload_to=upload_docs)

my 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})

i much appreciate your helps , please if you know something about it let me know , thank you so much

artiest
  • 554
  • 5
  • 20

1 Answers1

1

You need to draw first then get the content.


For how to do multiple capture.

You can reuse the same canvas, the toDataURL is a snapshot of current canvas.

Here is an example.

const player = document.getElementById('player')
const canvas = document.getElementById('canvas')
const form = document.getElementById('form')
const docs = document.getElementById('document')
const captureButton = document.getElementById('capture')
const context = canvas.getContext('2d')


captureButton.addEventListener('click', (e) => {
  context.drawImage(player, 0, 0, canvas.width, canvas.height)
  // this is just an example, you need a <input> so it's send by form (or use async request)
  let new_image = document.createElement('img')
  new_image.src = canvas.toDataURL()
  form.insertAdjacentElement('beforeend',new_image)
});

navigator.mediaDevices.getUserMedia({video: true})
  .then((stream) => { player.srcObject = stream;})
form *{max-width:20vw;}
img{display:inline-block;}
canvas{display:none;}
<form id="form" action="" method="POST" enctype="multipart/form-data">
  <video id="player" controls autoplay></video>
  <button type="button" id="capture">Capture</button>
  <button>save</button>
  <canvas id="canvas" width=320 height=240></canvas>
</form>

https://jsfiddle.net/271pvxa3/

apple apple
  • 10,292
  • 2
  • 16
  • 36
  • thank you so much , do you familiar with django ? if yes , how to save all of the captured image into the database? – artiest Sep 30 '21 at 15:59
  • can i make an input `` to save the captured images – artiest Sep 30 '21 at 16:04
  • 1
    @HunarMohammed I'm not familiar with django. maybe post a new question for that? – apple apple Sep 30 '21 at 16:10
  • 1
    @HunarMohammed you can try [use same name for all images](https://stackoverflow.com/a/2906814/5980430) or [ajax with FormData (same idea but in ajax form)](https://stackoverflow.com/questions/12989442) – apple apple Sep 30 '21 at 16:11
  • sorry , do you have something to add please https://stackoverflow.com/questions/69404704/how-to-access-to-image-html-tag-from-djangos-view – artiest Oct 01 '21 at 11:33
  • because we cant get the img tag from views , i want to add all base64 codes into an input type="text" then i will split them by its data attribute , but it only saves the last picture ? thank you – artiest Oct 01 '21 at 11:46
  • 1
    @HunarMohammed the `document.createElement('img')` is just for demonstration, you need to create a `` so form send it. – apple apple Oct 01 '21 at 13:47
  • yes , but i want to sent all encode data to inputs , it only save the last image , i sent all encode data to an input tag then i split the data by `data` from the view (backend-python) – artiest Oct 01 '21 at 14:20
  • we cant iterate over all captured images and send them to separate input tags , isnt there any other solution please . i much appreciate your helps ... – artiest Oct 01 '21 at 14:34
  • @HunarMohammed what actually not work? why you cannot iterate over all captured images. It seems better to ask new question with updated examples. – apple apple Oct 02 '21 at 07:10
  • https://stackoverflow.com/questions/69415265/how-to-add-multiple-values-to-an-input-tag-js can you check it out please – artiest Oct 02 '21 at 08:53