PHP Tutorial: Creating A MemeGenerator / Cheezburger Clone - Part 2
|May 9, 2012||Posted by Greg Bulmash under PHP|
Part II: Adding Text To Your Image
In Part 1 of this series, I dealt with installing ImageMagick, installing the Imagick extensions for PHP, creating an .htaccess file that lets you run scripts with .jpg extensions, and last, a simple script that uses ImageMagick to load a picture and deliver it to the browser.
Today I'll talk about adding the text to it. There are two things we want to consider when we do this. The text and the stroke.
First, you want to pick a font you like that is free for commercial use and has a good thickness. I chose Eau, which I found at Font Squirrel. I grabbed a few others too, and as I iterate this script out over the next couple of posts, I'll add them.
Second, you need to stroke your text. Even against a solid color background, it helps make the text a lot more readable. Against a multicolored background, it can be vital for readability.
Before we get into the script, I'll demo it, and then we can look at how it works.
And the script for
preview.jpg has grown...
<?php //get our text $text = ""; if(isset($_GET["text"])) $text = $_GET["text"]; //if the text is longer than 80 chars, use just the first 80 if(strlen($text) > 80) $text = substr($text1,0,79); //set the font, size, colors, etc. //these could be set from URL parameters $font="fonts/eau.ttf"; $fontsize=25; $strokecolor="#000000"; $fontcolor="#FFFFFF"; $strokewidth=1; //Create our base image as an image magick object $img = new imagick('pbzoosm.jpg'); // set colors for the font and stroke // set both to the stroke color because $strokepixel = new imagickPixel(); $strokepixel->setColor($strokecolor); $fontpixel = new imagickPixel(); $fontpixel->setColor($fontcolor); //Create an image magick draw object for the text //and set the properties. We'll print twice to create //a smooth stroke. So this time, fill and stroke are //the stroke color. $draw = new imagickDraw(); $draw->setFont($font); $draw->setFontSize($fontsize); $draw->setFillColor($strokepixel); $draw->setStrokeColor($strokepixel); $draw->setStrokeWidth($strokewidth * 2); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $draw->setGravity(Imagick::GRAVITY_NORTH); //North gravity is top center //Now draw the text on top of the image $img->annotateImage($draw,0,5,0,$text); //now change the fill color to the font color $draw->setFillColor($fontpixel); //and make the stroke transparent $draw->setStrokeAlpha(0); //draw the font in its color $img->annotateImage($draw,0,5,0,$text); //deliver the image to the browser header("Content-type: image/jpeg"); echo $img; ?>