Skip to content

Instantly share code, notes, and snippets.

@douglascabral
Created March 9, 2018 13:43
Show Gist options
  • Save douglascabral/61caef6b75e5117a8d74dad48974b77a to your computer and use it in GitHub Desktop.
Save douglascabral/61caef6b75e5117a8d74dad48974b77a to your computer and use it in GitHub Desktop.
Center text in image with PHP
<?php
// Variáveis de configuração
$width = 600;
$height = 180;
$fontsize = 17;
$angle = 0;
$font = './arial.ttf';
// Cria a imagem
$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $white);
// Calcula o tamanho do texto
$bbox = imagettfbbox($fontsize, $angle, $font, 'Powered by PHP: ' . phpversion());
// Coordenadas x e y para o texto
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2);
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2);
// Escreve o texto
imagettftext($im, $fontsize, $angle, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());
// Exibe a imagem no Browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment