Cybrix
Cybrix

Reputation: 3318

How to generate unique images from hashed informations with PHP GD?

Good day,

in the website I'm working on, I would like to display an unique image to the user generated with a hash from his email address.

Should I generate fractals ?

If so, how can I make em "unique" or more specifically, easier to recognize by the user who has just logged on ?

I pretty much like the associated user's images by Stackoverflow to their new users.

I am using PHP GD.

Thank in advance for any tips to achieve this.

Upvotes: 11

Views: 4115

Answers (2)

X 47 48 - IR
X 47 48 - IR

Reputation: 1488

This may help you; it's a simple implementation using the image intervention library.

function unique_image($string, $img_w = 400)
{
    $hash = hash('md5', $string);
    $bytes = mb_strlen($hash, '8bit');
    $image = Image::canvas($img_w, $img_w, array_map('ord', str_split(substr($hash, -3, 3))));

    # Set color blocks.
    $blocks = [];
    for ($i = 0; $i < $bytes; $i++) $blocks[floor($i / 3)][] = ord($hash[$i]);

    $image_area = pow($img_w, 2);
    $square_area = $image_area / count($blocks);
    $sqr_w = sqrt($square_area);
    $cols = floor($img_w / $sqr_w);
    $spacing = ($img_w - $cols * $sqr_w) / 2;

    for ($x = 0; $x < $cols; $x++) for ($y = 0; $y < $cols; $y++) {
        $p['x1'] = $spacing + $sqr_w * $x;
        $p['y1'] = $spacing + $sqr_w * $y;
        $p['x2'] = $spacing + $sqr_w * ($x + 1);
        $p['y2'] = $spacing + $sqr_w * ($y + 1);

        $image->rectangle($p['x1'], $p['y1'], $p['x2'], $p['y2'], function ($draw) use ($x, $y, $blocks) {
            $block = $blocks[$x + $y];

            # Set square background (RGB), and the border.
            $draw->background([$block[0], ($block[1] ?? 0), ($block[2] ?? 0)]);
            $draw->border(1.8, '#aaa');
        });
    }

    # Return image.
    return $image->response();
}

Upvotes: 0

Dan Mandle
Dan Mandle

Reputation: 5839

If you're looking to have it done remotely, you could use something like http://robohash.org/ or gravatar http://en.gravatar.com/site/implement/images/ (under the default section)

Upvotes: 1

Related Questions