Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cognitive Services: Computer Vision — Analyze an Image with JavaScript in WordPress with REST API
/**
* Get Image Alt Recognition with Computer Vision
* using Azure Cognitive Services.
*/
var WPAPI = require('wpapi');
var wp = new WPAPI({
endpoint: 'http://src.wordpress-develop.dev/wp-json'
});
/**
* Handle Image Alt Generation.
*/
function processImage() {
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
// Replace <Subscription Key> with your valid subscription key.
var subscriptionKey = "<Subscription Key>";
// You must use the same region in your REST call as you used to get your
// subscription keys. For example, if you got your subscription keys from
// westus, replace "westcentralus" in the URI below with "westus".
//
// Free trial subscription keys are generated in the westcentralus region.
// If you use a free trial subscription key, you shouldn't need to change
// this region.
var uriBase =
"https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/analyze";
// Request parameters.
var params = {
"visualFeatures": "Categories,Description,Color",
"details": "",
"language": "en",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputImage").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Make the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader(
"Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: '{"url": ' + '"' + sourceImageUrl + '"}',
})
.done(function (data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
// Extract and display the caption and confidence from the first caption in the description object.
if (data.description && data.description.captions) {
var caption = data.description.captions[0];
if (caption.text && caption.confidence >= 0.5) {
const imgDescription = caption.text;
// ⬆️ Upload to WordPress.
wp.media()
// Specify a path to the file you want to upload, or a Buffer
.file(sourceImageUrl)
.create({
title: imgDescription,
alt_text: imgDescription,
caption: imgDescription,
description: imgDescription
})
.then(function (response) {
// Your media is now uploaded: let's associate it with a post
var newImageId = response.id;
return wp.media().id(newImageId).update({
post: associatedPostId
});
})
.then(function (response) {
console.log('Media ID #' + response.id);
console.log('is now associated with Post ID #' + response.post);
});
}
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " :
errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
jQuery.parseJSON(jqXHR.responseText).message;
alert(errorString);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment