Created
July 15, 2020 08:31
-
-
Save epexa/546ac52987b07e9179e30e4c8c838b8d to your computer and use it in GitHub Desktop.
Adding text to all images from folder (directory) in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Adding text to all images from folder (directory) in PHP | |
Like this: https://addtext.com | |
And this API: https://cloudinary.com/documentation/image_transformations#adding_text_captions | |
LIBRARY: https://github.com/Intervention/image | |
INSTALL: | |
$ sudo apt install php-gd | |
$ sudo apt install composer | |
$ composer require intervention/image | |
*/ | |
const SOURCE_DIR = 'sources/'; | |
const TARGET_DIR = 'results/'; | |
const TEXT = 'Pied Piper'; | |
const LEFT = 178; | |
const TOP = 95; | |
const FONT_SIZE = 30; | |
const FONT_PATH = '/home/jared_dunn/dev/php/russfest/Ubuntu-L.ttf'; | |
const COLOR = '#fff'; | |
require 'vendor/autoload.php'; | |
use Intervention\Image\ImageManagerStatic as Image; | |
if ($handle = opendir(SOURCE_DIR)) { | |
while (false !== ($entry = readdir($handle))) { | |
if ($entry !== '.' && $entry !== '..') { | |
$img = Image::make(SOURCE_DIR . $entry); | |
$img->text(TEXT, LEFT, TOP, function($font) { | |
$font->file(FONT_PATH); | |
$font->size(FONT_SIZE); | |
$font->color(COLOR); | |
}); | |
$new_filename = TARGET_DIR . substr($entry, 0, -4) . '_' . random_int(1, 999) . '.png'; | |
$img->save($new_filename); | |
/* start output one image in browser */ | |
header('Content-type: image/png'); | |
readfile($new_filename); | |
/* end output one image in browser */ | |
} | |
} | |
} | |
closedir($handle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment