Cloudinary Blog

How to Build an Enhanced Gravatar Service, Part 1

How to Build an Enhanced Gravatar Service, Part 1

The advent of web development since 25 years ago has given birth to an abundance of online services that help developers build apps efficiently and smoothly. Gravatar is a shining example of such a service. Built by WordPress, Gravatar generates globally recognized avatars. Fun fact: 80 percent of Gravatar users first came across that service when reading a WordPress blog.

This is how it works: after uploading an image and creating your public profile on Gravatar, next time you log in to a Gravatar-enabled site or platform, that image and profile will automatically follow you there through Gravatar’s association of your email address with a hash and an avatar.

This post describes how to build a replica of Gravatar with more image-oriented features. You’ll likely find it eye opening and fun.

Sign up for Cloudinary free today!

Gravatar Features

Gravatar creates URLs according to the hashed value of email addresses, after which user avatars become accessible in the syntax<hash>, e.g.:

Here’s one wrapped in an <img> tag:

You can specify the size for the image by adding the s parameter, e.g.:

Absent the s parameter in the URL, Gravatar returns an 80x80 image by default.

You as developers can do the following with Gravatar:

  • Display a default image if the hash is invalid or if the user has no avatar attached to his or her email address.
  • Display a 404 error message if no image is attached to the hash.
  • Display a simple, cartoon-style silhouette by adding d=mp to the URL.
  • Return a generated robot with various colors and faces by adding _d=robohash to the URL.
  • Combine query parameters.
  • Add the r= or rating= parameter to the URL so that your users can denote whether their images are appropriate for certain audiences. Below are your value choices. Specify one to request images up to and including that rating.
    • g: Contains no offensive content, hence suitable for all audiences.
    • pg: Might contain rude gestures, provocatively dressed individuals, the lesser swear words, or mild violence.
    • r: Might contain harsh profanity, intense violence, nudity, or hard-drug use.
    • x: Might contain hard-core sexual imagery or extremely disturbing violence.

Clavatar: Your Own Enhanced Gravatar Service

Let’s call the enhanced Gravator service Clavatar, with which you can do the following:

  • Return a 100x100 image by default if the hash is invalid or if the user has no avatar attached to his or her email address.
  • Request for one of the following versions of an image by adding the related parameter to the URL:
    • Any size with the size (s) parameter, e.g., s=400 or size=400.
    • A cartoonized version with d=cp.
    • A black-and white version with d=bw.
    • An artistic version with d=hk.
    • A compressed and optimized version with q=auto.
    • The best format with f=auto. This version ensures the most suitable format for whichever browser is delivering the image.
    • A rounded-corners version (like the thumbnail on all platforms) with rc=y.
    • A color-bordered version with b=<color>, e.g., b=red.
  • Rotate the image with r=<angle>, e.g., r=40. The angle’s value must be between 1 and 100.

Development Process

The development process for Clavatar comprises three major steps.

Set Up a Lumen Project

  1. Install Composer and PHP on your development or production machine and then run this command:

    Copy to clipboard
    composer create-project --prefer-dist laravel/lumen clavatar
  2. Go to the clavatar directory and rename the env.example file to .env.

  3. Run the project with the command php -S localhost:8000 -t public.

Your Lumen project is now up and running.

Set Up the Mechanics for Database Access, Facades, and User Registration

1. Create a database called clavatar in your local MySQL server. 2. Uncomment these two lines in the bootstrap/app.php file to make available the Laravel Eloquent Object Relation Mapping (ORM) and Laravel facades for building the Clavatar capabilities:

// $app->withFacades(); // $app->withEloquent();

3. Create a user migration file with this command line:

Copy to clipboard

php artisan make:migration create_users_table ```

4. Add the following code to the file:

Copy to clipboard

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('users', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

5. Run php artisan migrate to run the migration.

6. Create a user controller with this command from the console:

Copy to clipboard
php artisan make:controller UserController

7. Add the following method for creating users to the UserController.php file:

Copy to clipboard

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class UserController extends Controller
public function createUser(Request $request)
        $name     = $request->get('name');
        $email      = $request->get('email');
        $password = Hash::make($request->get('password'));

        $credentials = $request->only('email');

        $user = User::where('email', $email)->exists();

        if($user) {
            return response()->json([
                'status' => false,
                'message' => 'User already exists. Please try with another email.'
            ], 401);

        $user = new User;
        $user->name      = $name;
        $user->email     = $email;
        $user->password  = $password;
        $user->hash      = md5(strtolower(trim($email)));

        return response()->json([
                'status' => true,
                'message' => 'User created successfully'
            ], 201);

The code above signs up users with their names, email addresses, and passwords. For each user, the code hashes the related email address with the MD5 function, as Gravatar does, saving the hash as a unique user identifier.

8. Add the following endpoint to the routes/web.php file:

Copy to clipboard
$router->post('users', 'UserController@createUser');

9. Add a user by invoking the API endpoint on Postman or Insomnia:


Associate Images With User Accounts

Next, build the feature that enables users to attach an image to their Clavatar accounts.

Completing this project also requires the following tasks, usually through a UI, which are beyond the scope of this post:

  1. Build a user-login process.
  2. Obtain a bearer token.
  3. Enable image uploads by users after authentication by middleware that verifies the bearer token.

To enable image uploads by users, do the following:

1. Install the Cloudinary PHP Library, version 2.0.0-Beta from your console:

Copy to clipboard
composer require "cloudinary/cloudinary_php:>2.0.0-beta"

With that library, you can perform these tasks on the back end: * Upload images synchronously and asynchronously. * Compress and optimize images through transformations. * Store and back-up images and other media files. * Deliver media files instantly.

2. Go to your Cloudinary dashboard and, under Account Details, copy the value of the API environment variable, which looks like this:


Paste it in the .env file of your project.

3. In your console, create an AvatarController.php file:

Copy to clipboard
php artisan make:controller AvatarController

Add the following uploadImage function to that file:

Copy to clipboard

namespace App\Http\Controllers;

use App\Models\User;
use Cloudinary\Cloudinary;
use Cloudinary\Transformation\Resize;
use Cloudinary\Transformation\Effect;
use Cloudinary\Transformation\Format;
use Cloudinary\Transformation\Quality;
use Cloudinary\Transformation\RoundCorners;
use Cloudinary\Transformation\ArtisticFilter;
use Cloudinary\Transformation\Border;
use Cloudinary\Transformation\Argument\Color;

use Illuminate\Http\Request;

class AvatarController extends Controller
    protected $cloudinary;

    public function __construct()
        $this->cloudinary = new Cloudinary(env('CLOUDINARY_URL'));

    public function uploadImage(Request $request)
        $image  = $request->file('image');
        $userId = $request->get('user_id');

        $uploadedImage = $this->cloudinary->uploadApi()->upload($image->getRealPath());

        if($uploadedImage) {

            User::where('id', $userId)->update(['avatar_id' => $uploadedImage['public_id']]);

            return response()->json([
                'status' => true,
                'message' => 'Upload successful'
            ], 200);

        return response()->json([
            'status' => false,
            'message' => 'Upload failed. Please try again'
        ], 500);

The above code did the following:

1. Imported the Cloudinary class.

2. Instantiated the Cloudinary class in the constructor, creating an object that connects with your Cloudinary account.

3. Added a function that accepts the user ID (user_id) and an image (image), uploads the image to Cloudinary, and updates your database with the image name returned from Cloudinary.

Copy to clipboard
$uploadedImage = $this->cloudinary->uploadApi()->upload($image->getRealPath()); // Uploads image to Cloudinary

User::where('id', $userId)->update(['avatar_id' => $uploadedImage['public_id']]); // Updates your DB with the name of the image, which is the public ID (`public_id`).

Here’s an example of Cloudinary’s response after an upload:

Copy to clipboard
  [public_id] => c87hg9xfxrd4itiim3t0
  [version] => 1571218607
  [signature] => f8645b000be7d717599affc89a068157e4748276
  [width] => 864
  [height] => 576
  [format] => jpg
  [resource_type] => image
  [created_at] => 2017-06-23T13:59:18Z
  [bytes] => 120253
  [type] => upload
  [url] =>
  [secure_url] =>

4. Add the Upload API endpoint to routes/web.php:

Copy to clipboard
   $router->post('upload', 'AvatarController@uploadImage');

As a test, upload an image (for example, the one specified by the URL below) with Postman or Insomnia:

Clavitar successful

Finally, verify the following:

  • The image you just uploaded is in your Cloudinary account’s Media Library.
  • The avatar_id value in your database is the same as the image’s public_id value.

You’ve now associated an image with a user.

Part 2 describes how to make Clavatar work like Gravatar and to develop Clavatar’s capabilities of enabling requests for various versions of the images related to user accounts. Stay tuned.

Recent Blog Posts

Partner news: Cloudinary-Getty Images Integration

Supported by intelligent automation, Cloudinary serves as an effective conduit between media asset management and delivery so you can take maximum advantage of assets, compress workflows, and build and coordinate engaging and inspiring customer experiences. Through Cloudinary’s Digital Asset Management (DAM) solution, which employs the company’s innovative image and video APIs, creative and marketing teams can benefit from them, as well as from many AI-powered and automated capabilities. As a result, you can transform, optimize, and deliver media at scale on an intuitive UI.

Read more
Why Audio in Video Matters

Many content creators and consumers tend to regard video as visuals, but that’s only part of the experience. Immersive video content includes strong audio. Just like in a movie, the audio for video content comprises many components: the narrator or subjects, the background music that sets the mood and draws viewers in, sound effects, and so forth.

Read more

For Developers: the HTML <picture> Element Explained

By Amarachi Amaechi
For Developers: the HTML <picture> Element Explained

We all know the good ol', tireless <img> element, which has been a long-time go-to for inserting graphics into webpages. Time doesn’t stop, however, and neither do technological advancements. So, let’s get you up to speed with the element’s modern alternative: the <picture> element.

Read more