Generating Image Placeholder Using PHP

There are tons of website provide placeholder for images to make our website looks nicer. But depending on other service sometimes a little bit of hassle, for example, sometimes they're running out of bandwidth. So, you have to make your own image placeholder. Luckily, it's easy using PHP.

$text = 'Hello';
$width = 600;
$height = 400;

$image = @imagecreatetruecolor($width, $height) or die("Cannot Initialize new GD image stream");

$backgroundColor = imagecolorallocate($image, 153, 153, 0);
imagefill($image, 0, 0, $backgroundColor);

$font = './Agave-Regular.ttf'; // Search and download this font
$fontSize = 12;
$textColor = imagecolorallocate($image, 255, 255, 255);

// Make the text centered
$textBox = imagettfbbox($fontSize, 0, $font, $text);
$textWidth = $textBox[2] - $textBox[0];
$textHeight = $textBox[7] - $textBox[1];

$x = ($width / 2) - ($textWidth / 2);
$y = ($height / 2) - ($textHeight / 2) + 1;

imagettftext($image, $fontSize, 0, $x, $y, $textColor, $font, $text);

header("Content-Type: image/png");

imagepng($image);
imagedestroy($image);
Connect with me:

Comments

Spammy comment will be deleted. Markdown syntax is supported.