Identicons as profile picture in your Angular Website

19 Aug by Vishal

Identicons as profile picture in your Angular Website

Reading Time: 2 minutes

Identicons are visual representations of hash value, usually ip address, that serves to identify a user of a computer system as a form of avatar.

We can use this in our application to create a basic unique profile picture for each identical user. This will help not only in creating unique picture for each user but also serves a best way to hide informations behind a picture.

In the following post I am going to show how to create identicons from the unique mail id and use it as a profile picture in your application.

Start the application using angular cli and create a basic project ( I am not going to show how to start a basic angular application as it will increase the post length and make you bored easily )

Dependencies for Identicons

Following dependencies need to be added

  1. Spark-md5 – For creating hash code of mail id

We are going to use GRAVATAR for creating our identicons. Following is the url that will create identicons from hashcode that is passed into it.

https://www.gravatar.com/avatar/<hashcode>?d=identicon

<hashcode> = Change this with the unique hash code

Starting the Identicons App

Lets start the application by fetching mail id from user

<input type="email" [(ngModel)]="email" placeholder="Enter your Mail ID">

<button (click)="submit()">Generate Identicon</button>

The above line will create a input box and a button to generate identicon.

Now lets create that submit function in the component.ts

submit() {

    this.generatedHash = sparkmd5.hash(this.email);

     }

You can now see how I created a simple hashcode using spark-md5 module. Now as explained before we need to pass this hashcode into that url. Lets create a simple function to do this.

// Generate identicon
createIdenticon(emailHash: any): string {
return 'https://www.gravatar.com/avatar/' + emailHash + '?d=identicon';
}

Now we can simply pass that hashcode into this function and will provide you the url which can then be used inside [src] attribute of <img> tag to make it visible in the screen

Lets see how submit function got changed

submit() {

    this.generatedHash = sparkmd5.hash(this.email);

    this.avatar = this.createIdenticon(this.generatedHash);

  }

Now see how html changed to make that image to view in the screen

<input type="email" [(ngModel)]="email" placeholder="Enter your Mail ID">

<button (click)="submit()">Generate Identicon</button>

<span>Your unique Hash: {{generatedHash}}</span>

<div *ngIf="avatar">

  <img [src]="avatar">  

</div>

Below is the live demo of the above code. If you like this then subscribe to this blog and we will send you notification for each and every post that we put here. If you have any recommendations do let us know and we will create it for you.

Leave a Reply

Your email address will not be published. Required fields are marked *