Created
September 13, 2014 17:29
ImgurDownloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <curl/curl.h> | |
#include <curl/easy.h> | |
#include <curl/curlbuild.h> | |
#include <sys/stat.h> | |
#include <SFML/Graphics.hpp> | |
#include <Thor/Input.hpp> | |
using namespace std; | |
size_t write_data(void* ptr, const size_t size, const size_t nmemb, FILE* stream) | |
{ | |
return fwrite(ptr, size, nmemb, stream); | |
} | |
std::string random_string( size_t length ) | |
{ | |
auto randchar = []() -> char | |
{ | |
const char charset[] = | |
"0123456789" | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
"abcdefghijklmnopqrstuvwxyz"; | |
const size_t max_index = (sizeof(charset) - 1); | |
return charset[ rand() % max_index ]; | |
}; | |
std::string str(length,0); | |
std::generate_n( str.begin(), length, randchar ); | |
return str; | |
} | |
CURL* curl; | |
FILE* fp; | |
CURLcode res; | |
void get(string url, FILE* fp) | |
{ | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); | |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); | |
res = curl_easy_perform(curl); | |
} | |
void grab_image() | |
{ | |
remove("out.png"); | |
string begin = "http://i.imgur.com/"; | |
string file = ""; | |
string url = ""; | |
url+=begin; | |
url+=file; | |
url+=".png"; | |
struct stat st; | |
stat("out.png", &st); | |
st.st_size=0; | |
if (curl) | |
{ | |
// Open file | |
fp = fopen("out.png", "w"); | |
if( fp == NULL ) cout << "File cannot be opened"; | |
printf("Searching for image...\n"); | |
while (st.st_size == 0) | |
{ | |
timeval t1; | |
gettimeofday(&t1, NULL); | |
srand(t1.tv_usec * t1.tv_sec); | |
url = ""; | |
file = random_string(5); | |
url+=begin; | |
url+=file; | |
url+=".png"; | |
get(url, fp); | |
stat("out.png", &st); | |
} | |
curl_easy_cleanup(curl); | |
fclose(fp); | |
} | |
if (st.st_size > 0) | |
{ | |
printf("Found Image: %s\n", url.c_str()); | |
} | |
else { | |
printf("Tried and failed to find an image.\n"); | |
} | |
} | |
int main() | |
{ | |
curl = curl_easy_init(); | |
grab_image(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment