Last updated: August 25, 2026.
PHP’s GD extension can create charts, badges, placeholders, and other small raster images at request time. The endpoint must send an image content type and must not output whitespace or error text before the image data.
Create a simple status badge
<?php
declare(strict_types=1);
$label = trim((string) ($_GET['label'] ?? 'Ready'));
$label = mb_substr($label, 0, 30);
$image = imagecreatetruecolor(360, 90);
if ($image === false) {
http_response_code(500);
exit;
}
$background = imagecolorallocate($image, 34, 113, 177);
$textColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background);
imagestring($image, 5, 24, 35, $label, $textColor);
header('Content-Type: image/png');
header('Cache-Control: public, max-age=300');
imagepng($image);
imagedestroy($image);Use imagecreatetruecolor() for full-color output. Built-in bitmap fonts are useful for small labels; use imagettftext() with a server-side font file when typography matters.
Production considerations
- Bound image dimensions and input length to protect memory.
- Never accept an arbitrary server file path or remote image URL.
- Cache images whose output is determined by stable parameters.
- Log errors instead of displaying them inside the binary response.
- Use SVG or ordinary HTML/CSS when a raster image is unnecessary.
The PHP GD manual lists supported formats and drawing functions.