Skip to content

Instantly share code, notes, and snippets.

@lennis-dev
Last active June 1, 2024 14:52
Show Gist options
  • Save lennis-dev/a7916afb5147ff48d216c74548ec51ed to your computer and use it in GitHub Desktop.
Save lennis-dev/a7916afb5147ff48d216c74548ec51ed to your computer and use it in GitHub Desktop.
Function for creating Identicons.
<?php
/**
* Generate a unique Image based on a input string
* @param string $data
* @return string A SVG image
*/
function unique_img(string $data, string $background = "#000"): string
{
$hash = hash("sha512", $data);
$svg_data = '<rect x="0" y="0" width="128" height="128" fill="' . $background . '" />';
for ($i = 0; $i < 8; $i++) {
for ($i1 = 0; $i1 < 8; $i1++) {
if ($i % 2 == 0) {
if ($i1 % 2 == 0) {
$r = hexdec(substr($hash, ($i + 1) * ($i1 + 1), 1)) * 0.5;
} else {
$r = hexdec(substr($hash, ($i + 1) * ($i1 + 1), 1)) * 0.75;
}
} else {
if ($i1 % 2 == 0) {
$r = hexdec(substr($hash, ($i + 1) * ($i1 + 1), 1)) * 0.75;
} else {
$r = hexdec(substr($hash, ($i + 1) * ($i1 + 1), 1)) * 0.5;
}
}
$svg_data .= '<circle cx="' . (8 + 16 * $i1) . '" cy="' . (8 + 16 * $i) . '" r="' . $r . '" />';
}
}
$svg_color = 'hsl(' . round(hexdec(substr($hash, 0, 2)) * 1.40625) . ', 100%, 50%)';
return '<?xml version="1.0" encoding="utf-8"?>' . "\n" . '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" fill="' . $svg_color . '">' . $svg_data . '</svg>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment