PHP

Generate Identicon Avatar

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Render a deterministic 5x5 symmetric "identicon" placeholder avatar from any seed (usually a user's email or username). No external service — pure GD.
PHP
Raw
<?php
function identicon(string $seed, int $size = 200): string {
    $hash = md5($seed);
    $bytes = [];
    for ($i = 0; $i < 15; $i++) $bytes[] = hexdec($hash[$i]) % 2;   // 5 cols × 3 rows

    $img = imagecreatetruecolor($size, $size);
    $bg  = imagecolorallocate($img, 240, 240, 240);
    $fg  = imagecolorallocate($img, hexdec(substr($hash, 0, 2)), hexdec(substr($hash, 2, 2)), hexdec(substr($hash, 4, 2)));
    imagefill($img, 0, 0, $bg);

    $cellW = $size / 5;
    $cellH = $size / 5;
    for ($x = 0; $x < 3; $x++) {
        for ($y = 0; $y < 5; $y++) {
            if ($bytes[$x * 5 + $y]) {
                imagefilledrectangle($img, (int)($x * $cellW), (int)($y * $cellH), (int)(($x+1) * $cellW), (int)(($y+1) * $cellH), $fg);
                // mirror to right side (col 3 → col 1, col 4 → col 0)
                if ($x < 2) {
                    imagefilledrectangle($img, (int)((4-$x) * $cellW), (int)($y * $cellH), (int)((5-$x) * $cellW), (int)(($y+1) * $cellH), $fg);
                }
            }
        }
    }

    ob_start();
    imagepng($img);
    imagedestroy($img);
    return ob_get_clean();
}

file_put_contents('avatar.png', identicon('alice@example.com'));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.