Skip to content

Instantly share code, notes, and snippets.

@epexa
Created July 15, 2020 08:31
Show Gist options
  • Save epexa/546ac52987b07e9179e30e4c8c838b8d to your computer and use it in GitHub Desktop.
Save epexa/546ac52987b07e9179e30e4c8c838b8d to your computer and use it in GitHub Desktop.
Adding text to all images from folder (directory) in PHP
<?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