Skip to content

Instantly share code, notes, and snippets.

@luveti
Created August 27, 2015 15:22
Show Gist options
  • Save luveti/a069d187498ceee71770 to your computer and use it in GitHub Desktop.
Save luveti/a069d187498ceee71770 to your computer and use it in GitHub Desktop.
Download random google images in a specific format
var fs = require('fs');
var url = require('url');
var path = require("path");
var request = require('sync-request');
var base_url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=";
function downloadImages(type) {
var res = JSON.parse(request('GET', base_url + type + '&as_filetype=' + type + '&start=' + Math.floor((Math.random() * 50) + 1)).body.toString('utf-8'));
if(res['responseData']['results']) {
var images = res['responseData']['results'];
images.forEach(function (image, i) {
var last_slash_after_period = image.url.indexOf('/', image.url.lastIndexOf('.'));
images[i] = (last_slash_after_period == -1) ? image.url : image.url.substring(0, last_slash_after_period);
var local_filename = path.basename(url.parse(images[i]).pathname);
if(!fs.existsSync('test_images/' + local_filename)) {
console.log("Downloading '" + local_filename + "'");
fs.writeFileSync('test_images/' + local_filename, request('GET', images[i]).body);
}
else {
console.log("Skipping '" + local_filename + "'");
}
});
}
}
// repeat the download process 10 times for each image type
for(var i = 0; i < 10; i++) {
downloadImages('png');
downloadImages('jpg');
downloadImages('gif');
downloadImages('bmp');
}
console.log('Done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment