Skip to content

Instantly share code, notes, and snippets.

@nicolastorre
Last active February 22, 2017 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolastorre/b9df16eb4880d9d76c1d814dd590895a to your computer and use it in GitHub Desktop.
Save nicolastorre/b9df16eb4880d9d76c1d814dd590895a to your computer and use it in GitHub Desktop.
[PHP] How to print text on a jpeg image
<?php
// URL of the font to be downloaded
$fontURL = "http://www.font-police.com/classique/sans-serif/arial.ttf";
// Test if the filepath is in parameters and the file exists
if(empty($argv[1]) || !file_exists($argv[1])) {
echo "A valid Image path is required! The command syntax is 'php writeTextOnImage.php <input_image_filepath> <input_image_filepath> '<string_to_write>'";
exit();
}
// Set the image filepath
$inImagePath = $argv[1];
// Set Text to Be Printed On Image
$text = !empty($argv[3]) ? $argv[3] : "Hello world!";
// Name and path of the output image file
$outImageName = !empty($argv[2]) ? $argv[2] : "output.jpeg";
$outImagePath = __DIR__ ."/". $outImageName;
// Text size, angle, x and y position
$textOptions = array(
"size" => 75,
"angle" => 20,
"xPos" => 100,
"yPos" => 400
);
// Create Image From Existing File
$inImg = imagecreatefromjpeg($inImagePath);
// Make some colors
$white = imagecolorallocate($inImg, 255, 255, 255);
$grey = imagecolorallocate($inImg, 128, 128, 128);
$black = imagecolorallocate($inImg, 0, 0, 0);
// Download font file and set the font path
$font = file_get_contents($fontURL);
$fontName = basename($fontURL);
$fontPath = __DIR__ ."/". $fontName;
file_put_contents($fontPath, $font);
// Write text on image
if(file_exists($fontPath)) {
imagettftext($inImg, $textOptions['size'], $textOptions['angle'], $textOptions['xPos'], $textOptions['yPos'], $white, $fontPath, $text);
}
// Write Image to path 'output.jpg'
imagejpeg($inImg, $outImagePath);
// Flush memory
imagedestroy($inImg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment