Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created July 26, 2012 09:52
Show Gist options
  • Save k-holy/3181277 to your computer and use it in GitHub Desktop.
Save k-holy/3181277 to your computer and use it in GitHub Desktop.
GDでTTF
<?php
/**
* GDでTTF
* @author [email protected]
*/
$fontFile = __DIR__ . DIRECTORY_SEPARATOR . 'yojo.ttf';
$text = (isset($_GET['text'])) ? $_GET['text'] : null;
$fontSize = (isset($_GET['size']) && ctype_digit($_GET['size'])) ? intval($_GET['size']) : null;
if (!isset($text)) {
$text = 'てスト';
}
if (!isset($fontSize) || $fontSize < 1 || $fontSize > 70) {
$fontSize = 70;
}
$textAngle = 0;
$padding = $fontSize / 2 + 20;
$boundingBox = imagettfbbox($fontSize, $textAngle, $fontFile, $text);
$minX = min(array($boundingBox[0], $boundingBox[2], $boundingBox[4], $boundingBox[6]));
$maxX = max(array($boundingBox[0], $boundingBox[2], $boundingBox[4], $boundingBox[6]));
$minY = min(array($boundingBox[1], $boundingBox[3], $boundingBox[5], $boundingBox[7]));
$maxY = max(array($boundingBox[1], $boundingBox[3], $boundingBox[5], $boundingBox[7]));
$left = abs($minX) - 1;
$top = abs($minY) - 1;
$textWidth = $maxX - $minX;
$textHeight = $maxY - $minY;
$imageWidth = $textWidth + $padding;
$imageHeight = $textHeight + $padding;
$image = imagecreate($imageWidth, $imageHeight);
$bgColor = imagecolorallocate($image, 0xff, 0xff, 0xff);
$textColor = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 0, 0, $imageWidth, $imageHeight, $bgColor);
imagettftext(
$image,
$fontSize,
$textAngle,
$left + ($imageWidth / 2) - ($textWidth / 2),
$top + ($imageHeight / 2) - ($textHeight / 2),
$textColor,
$fontFile,
$text
);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment