What is the best way to encode an image into JSON format?

let canvas = document.createElement('canvas');
let context = canvas.getContext( '2d' );
context.drawImage( video, 0, 0 );
let image_src = canvas.toDataURL('image/jpeg');
let dataURL = canvas.toDataURL("image/jpeg");
let image= dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log(image);

let params = {
  // Request parameters
  "returnFaceId": "true",
  "returnFaceLandmarks": "false",
  "returnFaceAttributes": "age",
};

$.ajax({
  url: "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + $.param(params),
  beforeSend: function(xhrObj){
    // Request headers
    xhrObj.setRequestHeader("Content-Type","application/octet-stream");
    xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","8b99a9ed839a40a08aa8b529ef0f9b8c");
  },
  type: "POST",
  // Request body
  data: [image],
})

This Javascript code captures an image and then passes it to a JSON object. However, the request always receives a response of 400. You can find more information about the Microsoft API here:

Here is a screenshot of the API documentation.

Can you provide any hints on how to properly pass the image?


https://i.sstatic.net/qVYqA.png


Answer №1

UPDATE

After spending some time experimenting with this, I discovered that the reason for the failure in your example was due to sending base64 data instead of binary data, which is required by the API. The challenge then lies in converting an image to a blob. I have created a JSFiddle with the code below that effectively generates this binary blob from a canvas loaded with an image randomly fetched from a URL. It successfully elicits a 200 response from the API. Take a look at it and feel free to ask if you have any queries:

https://jsfiddle.net/mq70h6pf/14/

function getImageBlob(url, callback) {
    var image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.src = url;
    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth;
        canvas.height = this.naturalHeight;
        canvas.getContext('2d').drawImage(this, 0, 0);
        canvas.toBlob(callback);
    };
}

var randomImageUrl = "https://unsplash.it/200/300/?random";
getImageBlob(randomImageUrl, function(imageBlob) {
    $("#displayImage").attr("src", URL.createObjectURL(imageBlob)); //Verify if blob can be displayed correctly, for reference only
    console.log(imageBlob);
    var params = {
      // Request parameters
      "returnFaceId": "true",
      "returnFaceLandmarks": "false",
      "returnFaceAttributes": "age",
    };
    $.ajax({
      url: "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + $.param(params),
      beforeSend: function(xhrObj){
        // Request headers
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","8b99a9ed839a40a08aa8b529ef0f9b8c");
      },
      type: "POST",
      contentType: "application/octet-stream",
      // Request body
      data: imageBlob,
      processData: false
    })
});

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

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

XMLHttpRequest Refusing to Send Data

This snippet of code is crucial for the custom extension: let url = "https://mywebsite.com/data.php"; function sendRequest() { var client = new XMLHttpRequest(); client.open("POST", url, true); client.setRequestHeader("Content-Type", "text/pla ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

After AJAX has been loaded, Readmore.js fails to function properly

I am currently struggling to get the Readmore.js plugin working with AJAX content. The code snippet I have included is not cutting off the content inside the .more element as expected. <td><div class="more"><?php echo $row['book_desc&a ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

Is there a way to include two functions within a single ng-click event?

Is it possible to incorporate two functions in a single ng-click event? Below is the code snippet: <button class="cButtonSpeichern" ng-click="saveUser()">Speichern</button> In addition, I would like to include this function as well. alert ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

Utilizing mapped data to display numerous Material-UI Dialog elements

On my table, I have a list of users displayed. Each user has a button in their row to delete them. Clicking the delete button triggers a Material-UI Dialog to confirm. An issue arises where 3 dialogs are being rendered due to mapping, and the last dialog ...

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

Using setTimeout with jQuery.Deferred

I decided to experiment with jQuery Deferred and setTimeout by creating a basic list. <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> In my script, I ...

Guide on displaying API data within nested fields in ReactJS

import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants' export const addToCart = (uid, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/v1/`) dispatch({ ...

Issue with camera boundaries in Three.js when using EffectComposer with an orthogonal camera is currently presenting inaccuracies

In reference to a previous question on Three.js, I have successfully created a scene with a "minimap" using an orthogonal camera rendering into a viewport. The minimap is displayed properly in the standard renderer. Now, I wanted to add postprocessing eff ...

How can I attach a cookie to a div that becomes visible after a few seconds of video playback?

After 20 seconds of video play, a div element appears. I am trying to set up a cookie so that once the div is shown, it continues to appear unless the user clears their cache (cookie logic). This is my current attempt - http://jsfiddle.net/9L29o365/ Any ...

What could be causing Django REST Framework to block non-GET requests with a 403 Forbidden error from all devices except for mine?

Currently in the process of developing a web app using a Django REST Framework API. It runs smoothly on the computer where it was created (hosted online, not locally), but when trying to access the website from another computer, all GET requests work fine ...

Ajax updates to an element are not reflected until the for loop has completed

I am looking for a way to print a series of numbers sequentially using AJAX. Here is an example of what I want to achieve: (each new line represents an update of the previous line!) Output is: 1 12 123 1234 12345 123456 ... I ...

Incorporate Web-GL sandbox effects into an HTML webpage

I am searching for a method to showcase a Web-gl shader obtained from GLSL Sandbox on the background of an HTML page. Yet, it seems there is no simple embeddable API available. How can I accomplish this task? Can I integrate this specific Shader into an H ...