Realtime Image Typesetting with PHP GD

Today I wanted to go over some of the really cool things that can be done with both jQuery and PHP’s Graphical library. To begin, let’s go ahead and take a look at the demo of what I will be breaking down over this tutorial.

Click to see demo of Business Card Builder

The Markup


<h3>Realtime Business Card Builder</h3>
<div class="preview">
    <img src="scripts/server-side.php" />
</div>

Notice how the preview image’s “src” attribute is not pointing to a graphical file, but rather a server side php script? This is important because although we could use PHP to render new images out on our web server on every change, its best to view a single rendering through a static image element.

The client side code


By simply building up a query string that contains the values of our form fields, we can get a realtime performance. The first thing we want to create is a variable named “base” that will contain our preview image’s “src” orignal attribute value.

var base = $(".preview img").attr("src");

We make the “base” variable so that we may reference to the original URL of the server side file later on.

Next we want to gather our image from server side when the document is done loading for the first time. By utilizing jQuery’s serialize we will gather all our form’s fields and their values and request our image from php like so:

var base = $(".preview img").attr("src");

//GATHER IMAGE FOR FIRST TIME
$(".preview img").attr("src",base+'?'+$("#realtime-form").serialize());

As you can see, we set our image’s source attribute to be that of our base url, plus a serialized string of all our form’s input names and values.

Finally we want to setup our keyup event so as the user types into any of our form inputs, a “change request” for our image to be updated will be sent to php.

var base = $(".preview img").attr("src");

//GATHER IMAGE FOR FIRST TIME
$(".preview img").attr("src",base+'?'+$("#realtime-form").serialize());

//KEYUP EVENT AND NEW IMAGE GATHER
$("input,textarea").keyup(function(){
	$(".preview img").attr("src",base+'?'+$("#realtime-form").serialize());	
});

Notice how within our new keyup event we are basicly repeating our previous step of gather our image the first time? This is how we both gather changes the user has made, and request a new version of our image at the same time.

The server side code


Now lets take a look at our PHP image rendering file. The first thing we want to do in this file is to declare what format of image should it be rendering:

header ("Content-type: image/png");

We pass a content type of “image/png” to our files header so that we can have alpha transparency ability that is natural to png image formats.

Next we need to gather every possible value that is being sent to this file via our URI string. We do this by creating new variables and setting their value to each URI string value, like so:

$companyName = $_GET["companyName"];
$companySlogan = $_GET["companySlogan"];
$fullName = $_GET["fullName"];
$jobTitle = $_GET["jobTitle"];
$businessAddress = $_GET["businessAddress"];
$businessAddress = str_replace("\\n","\n",$businessAddress);
$businessAddress = str_replace("\\","",$businessAddress);
$phoneOne = $_GET["phoneOne"];
$phoneTwo = $_GET["phoneTwo"];
$emailAddress = $_GET["emailAddress"];
$siteUrl = $_GET["siteUrl"];

Notice how on some of the value gatherings I am using a str_replace() function? Again, we are replacing any instance of our hard return character (\\n) into an actual hard return upon rending our image and copy.

Next we are going to gather a temp image we will use to create the actual image we render on dynamically, like so:

$handle = $img = imagecreatefrompng( 'template.png' );

(‘template.png’ is a image file that lives on your server.)

Now we need to setup a few more variables that will come in handy when rendering our results:

$brown = ImageColorAllocate ($handle, 84, 48, 26);
$lightBrown = ImageColorAllocate ($handle, 145, 116, 94);
$white = ImageColorAllocate ($handle, 255, 255, 255);
$peach = ImageColorAllocate ($handle, 238, 222, 200);

We setup different font colors by making use of the “ImageColorAllocate()” PHP GD function and assigning it to our new “template.png” image ($handle). The array of numbers that proceeds “$handle” are RGB color values.

Now that we have everything (variable wise) setup to render our image, we need to place and setup our text in our image. Here is an example of how to do just that.

//company name
ImageTTFText ($handle, 18, 0, 20, 35, $brown, "timesbd.TTF", $companyName);

By using the “ImageTTFText()” PHP GD function, we can setup an array of parameters to place and render our copy in our image.
First, we point to our “template.png” image ($handle) want to place this copy onto. Next is an array of numerical values and they are in order as follows:

  • Font Size of Copy
  • Rotation of Copy
  • X Position to Image’s size
  • Y Position to Image’s size

You also need to avoid having the drug with some kind of beverage or alcohol can have an adverse effect on the buy professional viagra rat’s ovary follicles, uterus lining and decreased the amount of cilia in their fallopian tubes. Gupta, an Impotence Spesecretworldchronicle.com orden viagra viagrat in Delhi. It has been proven that overweight men are more viagra lowest price likely to suffer from heart, sexual and other health issues. Like all the impotency drugs, this drug too has an active ingredient which has a significant role on how well you play in the intimating session. levitra viagra price
After the “size, rotation and position” values, we set our desired font color via our pre-defined color variables. Next we can choose to use a custom font file that live along side this php file. Last is the copy value it’s self that we gathered from our URI string and turned into variables.

The very last part to rending our image with PHP GD, is to do some clean up work like so:

imagealphablending( $handle, false );
imagesavealpha( $handle, true );
ImagePng ($handle);
imagedestroy( $handle );

We finish off our file format of “.png” and its transparency, and lastly destroy the image when completed to free up server memory.

(Some may notice that the web address copy is rendered from an align of center on out, I show this example in the demo download.)

That’s it everyone! With a little JavaScript and PHP GD you can do some really cool stuff, and I hope to see some great examples soon.

~ Download a copy of the demo

Devin R. Olsen

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:TwitterFacebookGoogle Plus

17 Responses to “Realtime Image Typesetting with PHP GD”

  1. hermes logistik group uk Realtime Image Typesetting with PHP GD | Devin R. Olsen Web Developer

  2. Devin R. Olsen Sivaprabu Ganesan says:

    How to save the generated file in server side

  3. Devin R. Olsen Pankaj says:

    Hello This is very good article but how to use loadding image when we enter text and image generate.because server takes time to change image.

  4. Devin R. Olsen root_54 says:

    Response for :
    Minime says:
    NOVEMBER 2, 2011 AT 5:59 AM

    input in server-side.php :
    /* /fonts/ est le répertoire ou vous stockerez la police utilisée. */
    putenv(‘GDFONTPATH=’.$_SERVER[“DOCUMENT_ROOT”].’http://localhost/scripts’); //

  5. Devin R. Olsen Ryan says:

    I know this is an older article, but I can not for the life of me figure out why this will not work on my server. The preview img tag in the demo points to the server-side.php hosted here. When I change it to a relative path it doesn’t work.

  6. Devin R. Olsen Krzysiek says:

    no line break

  7. Devin R. Olsen Minime says:

    Excuse me ! The code of the realtime-phpgd.zip does work correctly :
    1) if i replace the line of the index.html
    img src=”http://www.devinrolsen.com/wp-content/themes/dolsen/demos/ajax/gd-realtime/scripts/server-side.php”
    to
    img src=”scripts/server-side.php”
    the file server-side.php not generate the new image…
    I don’t understand for run corretly in my http://localhost
    help me, please.

  8. Devin R. Olsen Minime says:

    Excuse me ! The code of the realtime-phpgd.zip does work correctly :
    1) if i replace the line of the index.html

    to

    the file server-side.php not generate the new image…
    I don’t understand for run corretly in my http://localhost
    help me, please.

  9. Devin R. Olsen Onweb says:

    I mean color, size, position …

  10. Devin R. Olsen Onweb says:

    I want to send the variables from a form but I have problems sending the color with a select ….

  11. Devin R. Olsen TSei says:

    Nice tutorial, Thanks!

  12. Devin R. Olsen CharlesL says:

    I am getting some weird character spacing issues when I installed the demo on my site. At first I thought it was the font I was using (one different from your demo) but upon closer inspection I realized all of the fonts were acting weird… thoughts?

  13. Devin R. Olsen CharlesL says:

    Love the tutorial! I can’t get the zip to open. Any suggestions?

    • Hi CharlesL, glad you enjoyed the tutorial. Having been a while since I wrote this, I decided it was time for an update. There are now some changes that should help with both performance, legibility and code length. Now with that out of the way, please make sure you have an way to uncompressed the file with such programs as 7zip or winRar, from there you should have no problems opening up the zip file.

  14. Devin R. Olsen Ben says:

    Forget that last comment, I got it to unzip at last. Thank you.

  15. Devin R. Olsen Ben says:

    Devin, this is exactly what I’ve been looking for but unfortunately the zip file says it’s ‘invalid or corrupted’. Any chance of emailing me a working copy – would be hugely appreciate indeed.
    Many thanks,

    Ben

  16. Devin R. Olsen Hawkesley says:

    This is just what I need. Brilliant.
    I want to allow clients to make up the front cover of a submitted book manuscript and I think this approach could work.
    One problem I cant unzip the file. I am using a Mac. Could you check the file is Ok please?
    Thank you, very original.

  17. […] This post was mentioned on Twitter by Rob Lloveras, Devin Olsen. Devin Olsen said: Real-time Image Typesetting with PHP GD and Ajax | Devin R. Olsen Web Developer http://t.co/3D5pFpw via @AddThis […]

  18. […] also cover how to use custom text colors, sizes, rotation and even fonts in our example demo…. [full post] Devin R. Olsen Devin R. Olsen Web Developer ajax tutorialsjavascript tutorialsphp […]

Leave a Reply