Created
August 16, 2019 08:42
-
-
Save LeaveAirykson/61a7e62a7b85b1ab85e25a183330650c to your computer and use it in GitHub Desktop.
Image placeholder php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP placeholder images | |
// Version: 0.1 | |
// Author: Hinerangi Courtenay - @sky_maiden | |
// Usage (all parameters are optional): | |
// <img src="placeholder.php?size=400x150&bg=eee&fg=999&text=Generated+image" alt="Placeholder image" /> | |
// Inspired by http://placehold.it/ | |
header ("Content-type: image/png"); | |
// Convert hex to rgb (modified from csstricks.com) | |
function hex2rgb($colour) | |
{ | |
$colour = preg_replace("/[^abcdef0-9]/i", "", $colour); | |
if (strlen($colour) == 6) | |
{ | |
list($r, $g, $b) = str_split($colour, 2); | |
return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b)); | |
} | |
elseif (strlen($colour) == 3) | |
{ | |
list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]); | |
return Array("r" => hexdec($r), "g" => hexdec($g), "b" => hexdec($b)); | |
} | |
return false; | |
} | |
// Dimensions | |
$getsize = isset($_GET['size']) ? $_GET['size'] : '100x100'; | |
$dimensions = explode('x', $getsize); | |
// Create image | |
$image = imagecreate($dimensions[0], $dimensions[1]); | |
// predefined random colours | |
$colors = array('ccc','ddd','eee','111','454545','cfcfcf'); | |
// Colours | |
$bg = isset($_GET['bg']) ? $_GET['bg'] : $colors[array_rand($colors)]; | |
$bg = hex2rgb($bg); | |
$setbg = imagecolorallocate($image, $bg['r'], $bg['g'], $bg['b']); | |
$fg = isset($_GET['fg']) ? $_GET['fg'] : '555'; | |
$fg = hex2rgb($fg); | |
$setfg = imagecolorallocate($image, $fg['r'], $fg['g'], $fg['b']); | |
// Text | |
$text = isset($_GET['text']) ? strip_tags($_GET['text']) : $getsize; | |
$text = str_replace('+', ' ', $text); | |
// Text positioning | |
$fontsize = 4; | |
$fontwidth = imagefontwidth($fontsize); // width of a character | |
$fontheight = imagefontheight($fontsize); // height of a character | |
$length = strlen($text); // number of characters | |
$textwidth = $length * $fontwidth; // text width | |
$xpos = (imagesx($image) - $textwidth) / 2; | |
$ypos = (imagesy($image) - $fontheight) / 2; | |
// Generate text | |
imagestring($image, $fontsize, $xpos, $ypos, $text, $setfg); | |
// Render image | |
imagepng($image); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment