Image Editing on macOS – Placing Text Over Image Without ImageMagick

command lineimage editingmacos

I have a png image file which I would like to overlay text onto, via the command line (for use in a Makefile). The text to be overlaid is dynamic, decided at the time the image is modified.

I am aware that I can install ImageMagick to do this, but I would prefer to use a method that only requires standard OS X along with Xcode's developer tools.

Is there a command (or sequence of commands, including AppleScript if necessary) that I can use to make this happen? (If there is, an example would be excellent.)

Best Answer

You could try using a scripting language that comes installed with OS X, such as PHP or Ruby, and write a command line script using that.

Here's an example using PHP:

<?php

/*
Usage
php addtext.php input.png "The text"
*/

//  The source image (taken from the command line argument)
$image = imagecreatefrompng($argv[1]);

//  The text (taken from the command line argument)
$text = $argv[2];

//  Red colour
$colour = imagecolorallocate($image, 255, 0, 0);

//  Change font as desired
$font = '/Library/Fonts/Impact.ttf';

//  Add the text
imagettftext($image, 20, 0, 20, 30, $colour, $font, $text);

//  Save the image
imagepng($image, 'out-image.png');

//  Free up memory
imagedestroy($image);

?>

Save this script to a file called something like addtext.php and then run it like this…

php addtext.php image.png "Some text to add"

This example script should output an image called out-image.png with the text added, using the Impact True Type font that's installed with OS X, in the same directory as the PHP script.

You may want to read up on PHP's imagettftext function to play around with the text rendering.

Something similar could be done in Ruby, Python, etc. but I'm not sure of the "in-built" image manipulation / creation commands / libraries that come installed with OS X for those scripting languages.

Hope this is a good starting point.