Developer Snippet Diary

GD library |Fetch images from a folder , write text ,and save them to other directory. ||PHP

Directory:

  • images/*.*
  • converted/*.*
  • index.php
  1. This code index.php will fetch images from images folder and display them on browser with an convert button
  2. when you click on convert it will write text ("Rizwan") on each image and save to converted directory.
<?php
echo '<input type="submit" value="convert" /><br/>';
define('IMAGEPATH', 'images/');

if (is_dir(IMAGEPATH)){
    $handle = opendir(IMAGEPATH);
}
else{
    echo 'No image directory';
}

$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
    $newfile = str_replace(' ', '_', $file);
    $directoryfiles[] = $newfile; //all images directory inside images folder
}

foreach($directoryfiles as $directoryfile){
    if(strlen($directoryfile) > 3){
    echo '<img width="100px" height="100px" src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';


    $img = imagecreatefromjpeg(IMAGEPATH.$directoryfile);
	$white = imagecolorallocate($img, 255, 255, 255);
    $fontSize = "18";
    $rotation = "270";
	$txt = "Hello World test";
	$font = "C:\Windows\Fonts\arial.ttf"; 
	//imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);
	//or
	$textcolor = imagecolorallocate($img, 255, 2, 5);
	$textCoords = imagettfbbox($fontSize, $rotation, $font, $txt);
    $x = 36;
    $y = 36;
    imagettftext($img, $fontSize, $rotation, $x, $y, $textcolor, $font, $txt);
    
	// OUTPUT IMAGE
	// header('Content-type: image/jpeg');
	// imagejpeg($img);
	// imagedestroy($jpg_image);
	imagejpeg($img, "converted/".$directoryfile, 100);

    }
}

closedir($handle);

function scrivi($scrivi, $p) {
    $imgResource = imagecreatefromjpeg($p);
    $textcolor = imagecolorallocate($imgResource, 255, 255, 255);
    $fontPath = "st.ttf";
    $fontSize = "18";
    $rotation = "270"; // counter-clockwise rotation
    $text = "this is a text";
    $textCoords = imagettfbbox($fontSize, $rotation, $fontPath, $text);
    $x = 36;
    $y = 36;
    imagettftext($imgResource, $fontSize, $rotation, $x, $y, $textcolor, $fontPath, $text);
    unlink($p);
    imagejpeg($imgResource, $p, 100);
    imagedestroy($imgResource);
}
?>
Posted by: R GONDAL
Email: rizikmw@gmail.com