-
Notifications
You must be signed in to change notification settings - Fork 0
/
bing.js
60 lines (55 loc) · 1.58 KB
/
bing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var xhr = new XMLHttpRequest();
var imageUrls = [];
var endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search";
var apiKey = "446fb5ff1b48443b80734e86da4d564c";
//shrinkImages();
// Entrypoint. Returns array of image urls.
function makeQuery(searchTerm, numResults, offset, callback) {
var query = "?q=" + searchTerm + "&count=" + numResults + "&offset=" + offset;
xhr.open('GET', endpoint+query, true);
xhr.setRequestHeader("Ocp-Apim-Subscription-key", apiKey);
xhr.send();
xhr.addEventListener("readystatechange", function(e) {
getJSON(e);
callback();
});
}
function getJSON(e) {
// State 4 = DONE, status 200 = success
if (xhr.readyState == 4 && xhr.status == 200) {
if (imageUrls.length != 0) {
imageUrls = [];
}
var response = JSON.parse(xhr.responseText);
// Prevent multiple DONE states from triggering.
xhr.onreadystatechange = null;
response.value.forEach(function(image) {
imageUrls.push(image.contentUrl);
});
// shrinkImages(response);
}
}
function shrinkImages(response) {
for (var i = 0; i < response.value.length; i++) {
var img = document.createElement('img');
img.src = imageUrls[i];
var scale = findScale(response.value[i].width, response.value[i].height);
img.width = scale[0];
img.height = scale[1];
document.body.appendChild(img);
}
}
function findScale(width, height) {
var x = Math.max(width, height);
var y = Math.min(width, height);
// flip x width and height if the width isn't the long side
var flip = (width != x);
y = (350 * y) / x;
x = 350;
if (!flip) {
return [x, y];
}
else {
return [y, x];
}
}