Unraveling base64 information to display an image in Django using JavaScript

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.

Answer №1

The key is to sketch first before extracting the content.


If you're wondering how to capture multiple images,

You can utilize the same canvas, where toDataURL captures the current canvas state.

Take a look at this illustration.

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 a sample, you'll need an <input> to send it via a form (or use an 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/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve data from a JSON gist by parsing it as a query string

I have a JavaScript-based application with three key files: index.html app.js input.json The app.js file references input.json multiple times to populate content in div elements within index.html. My goal is to enhance the functionality so that when acc ...

Choose from a variety of video play options

Being new to javascript, I've successfully combined two functions that control video playback, but they seem to be conflicting with each other. The first function is designed to offer custom pause and play controls for the video // VIDEO CONTROLS STA ...

What is the best way to navigate users to a different page using AJAX upon receiving a successful response from PHP?

I am currently using a JavaScript function that is functioning correctly. It retrieves all error messages from the PHP file and displays them in a span with the ID "resto" without any issues. However, I now have a requirement where if the PHP file return ...

Tips for adjusting image hues in Internet Explorer?

I have successfully altered the colors of PNG images in Chrome and Firefox using CSS3. Here is my code: #second_image{ -webkit-filter: hue-rotate(59deg); filter: hue-rotate(59deg); } <img src='http://i.im ...

Is there a way to utilize regular expressions in React to dynamically insert onclick events into specific words within a text block?

I've been experimenting with regular expressions in React to implement an onclick event for each word in a text. I've attempted two different strategies, but neither has been successful thus far. Initially, I tried: return( <div> & ...

Issues with the functionality of AngularJS router implementation

I have searched through various resources like Stack Overflow and other blogs, but unfortunately, I haven't been able to fix the routing issue in my AngularJS code. Although there are no error messages, the routing functionality doesn't seem to b ...

Having trouble pinpointing the issue with this particular if statement?

I am currently working on creating a form that compiles all entered data when the user fills out all fields. The form is connected to a PHP file and functions properly, but I encountered issues when implementing validation logic. The "Validation" section ...

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

JavaScript for_each loop

Is there a way to access the field index of a JSON-Array when looping through it? I am aware that there is no foreach-loop like in PHP. This is an example of my json: { 'username': 'Karl', 'email': '<a href=" ...

Tips on configuring a hidden input field to validate a form

I am currently attempting to create a blind input field using PHP that will validate if the input field is empty. If it's not empty, the message set up to be sent will not send. However, I have encountered several issues with the placement and wording ...

Display Django radio buttons in a formatted list using the mark_safe() function

Exploring the Issue In an effort to include HTML instructions and display bullet points in my form label, I utilized 'mark_safe()' within a form: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

Transferring data between Jade templates

In the process of building a compact CMS system prior to diving into Node.js websites using Express, Jade, and Bootstrap, I encountered a minor setback. To enhance modularity, I am employing includes for various components like the navigation header on th ...

Utilizing Django to eagerly load and eager load in general, the property decorator offers a seamless

Is it possible to implement eager loading for a property decorator in Django? Here is an illustration of my code: class Player(models.Model): roles = models.ManyToManyField(Role, related_name='players') @property def role(self): ...

Ways to extract the maximum value from a dataset formatted in JSON

My current project involves using highcharts to create data series for plotting the chart, which looks something like this: series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] I have been considering ...

Utilizing express and socket.io for seamless cross-domain communication

Is there a way to activate cross-domain functionality for express.io? I require it for a Cordova application, but when using Chrome, I get an error message saying "No 'Access-Control-Allow-Origin' header is present on the requested resource. Orig ...

Determining if a date has passed using moment.js, focusing solely on the date

Is it possible to determine if a date has passed based solely on the date itself? Currently, I am using !moment(moment().format("LLL")).isBefore(moment.unix(data.dueDate._seconds).format("LLL")). However, this approach also takes into account the time. F ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...