Skip to content

Instantly share code, notes, and snippets.

@saeedvir
Created February 19, 2020 14:46
Show Gist options
  • Save saeedvir/76386999605d4f51d4932518e49e424d to your computer and use it in GitHub Desktop.
Save saeedvir/76386999605d4f51d4932518e49e424d to your computer and use it in GitHub Desktop.
create png from text in php
<?php
$to_store ='test-file.png';
$img_data=null;
$fontSize = 20;
$imgWidth = 400;
$imgHeight = 80;
$angle = 0;
$font = 'font_name.ttf';
$img_data = imagecreatetruecolor($imgWidth, $imgHeight);
$bg_color = imagecolorallocatealpha($img_data, 0, 0, 0, 127);
$fg_color = imagecolorallocate($img_data, 255, 255, 255);
imagefill($img_data, 0, 0, $bg_color);
imagecolortransparent($img_data, $bg_color);
if(!is_array($text)){
$splitText = explode ( "\\n" , $text );
}else{
$splitText=$text;
}
$lines = count($splitText);
foreach($splitText as $txt){
$textBox = imagettfbbox($fontSize,$angle,$font,$txt);
$textWidth = abs(max($textBox[2], $textBox[4]));
$textHeight = abs(max($textBox[5], $textBox[7]));
$x = (imagesx($img_data) - $textWidth)/2;
$y = ((imagesy($img_data) + $textHeight)/2)-($lines-2)*$textHeight;
$lines = $lines-1;
imagettftext($img_data, $fontSize, $angle, $x, $y, $fg_color, $font, $txt);
}
imagepng($img_data, $to_store);
imagedestroy($img_data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment