Retrieving email Gravatar images

Below is a quick hack to retrieve and save Gravatars. Gravatar images come in various formats, but we don’t detect them here, just save the retreived image in ‘jpg’ format.

function save_gravatars($emails) 
    /* Downloaded Gravatars will be stored here */
    $images_path = "./gravatars/";
    $image_type = ".jpg";

    /* Can vary from 1px to 512px */
    $image_size = "40";

    /* Rating can be any of the following :
     * g: suitable for display on all websites with any audience type.
     * pg: may contain rude gestures, lesser swear words, mild violence.
     * r: may contain harsh profanity, intense violence, nudity.
     * x: absolutely not sutably for any public websites.
    $image_rating = "g";

    /* Default image to load if the email id does not have a Gravatar:
     * 404: do not load any image if none is associated with the email 
     *      hash, instead return an HTTP 404 (File Not Found) response
     * mm: (mystery-man)
     * identicon: a geometric pattern based on an email hash
     * monsterid: a generated 'monster' with different colors, faces
     * wavatar: generated faces with differing features and backgrounds
     * retro: 8-bit arcade-style pixelated faces
    $default_image = "404";

    foreach($emails as $email) 
        $url  = '';
        $url .= urlencode(md5($email)).$image_type;
        $url .= '?default='.$default_image;
        $url .= '&s='.$image_size.'&r='.$image_rating;

        $filename = str_replace("@", "_", $email) . $image_type;
        $fp = fopen($images_path . $filename, "w+");
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        $response = curl_exec($ch);


We use the ‘save_gravatars’ function as below.

/* An array of emails of which the Gravatars are to be retrieved */
$email_ids = array(",");


You may request images with size anywhere from 1px up to 512px, however users who have lower resolution images will find that requesting larger images will cause pixelation (lower quality) in the retrieved image.

Leave a Reply

Your email address will not be published.