Home arrow PHP arrow Page 2 - Create Picture IDs with Name Tags Using PHP

PHP Script to Write Text and Merge Images - PHP

PHP can be used to write text to images or even merge a source image to a target image. With this concept, it is possible to create open source ID creation software. The ID can contain a picture of a person and a name tag written in text (or even include an ID number). Keep reading to learn how this can be done.

TABLE OF CONTENTS:
  1. Create Picture IDs with Name Tags Using PHP
  2. PHP Script to Write Text and Merge Images
  3. Demo Project Implementation
By: Codex-M
Rating: starstarstarstarstar / 6
July 13, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

I have found a basic tutorial regarding the use of PHP to write text on images using the GD function/library here: http://blog.ninedays.org/2007/11/29/writing-text-to-images-with-php/. This was coded originally by Terri Ann in her post: "Writing text to Images with PHP."

Let's modify the source code at the above link to fit this application. Since this application uses GET statements, the input to PHP can be found in the URL (variables are bolded):

Example:

http://www.php-developer.org/opensourceidcreator/?name=Codex Meridian&idnumber=694569

You can improve this application by adding a web form and asking users to input their name and id number. You can even ask them to upload their image (as long as it conforms to the above listed specifications above) and template. But these features are not currently included in this tutorial.

For the purpose of illustrating the basic concept, we will focus on the PHP side of the application.

The following is the PHP script (comments and discussions in blue):

<?php 

// Set the environment variable for GD. It's useful for preventing GD related errors; read Item 4 below.

 

putenv('GDFONTPATH=' . Realpath('.'));

//Credits:

//Original code by Terri Ann "Writing text to Images with PHP" found here: http://blog.ninedays.org/2007/11/29/writing-text-to-images-with-php/

//Version 1- Improvement by Codex-m at PHPdeveloper.org to:

//1. Write more than one text from the user to be parsed to the PHP by two GET statements

//2. Allow merging of an additional image with the ID picture template, which is the person's ID picture.

//3. Assign new variables for the new text and images to be added.

//4. Add important line at the top:

// putenv('GDFONTPATH=' . realpath('.'));

// This will prevent "Warning: Could not find/open font problem resulting to Error: The server could not create this image."

// Check if the variables are not empty or else return an error.

if((empty($_GET['name']))&&(empty($_GET['idnumber']))) fatal_error('Error: No text specified.') ;

//Parse inputs using two GET statements and assign to a PHP variable.

//Use HTML_Entity_decode to convert all HTML entities to its applicable characters.

//Use PHP trim command to remove spaces at the beginning and the end of the inputs.

$name = trim(html_entity_decode($_GET['name']));

$idnumber = trim(html_entity_decode($_GET['idnumber']));

//Validate if name is a string and Id number is numeric.

if((!is_string($name))&&(!(is_numeric($idnumber))))

fatal_error('Error: Text not properly formatted.') ;

      

//CUSTOMIZABLE: Declare and define the font file, font size, colors, image file name and template name.

$font_file       = 'ambient.ttf';

$font_size    = 33 ; // font size in pts

$font_color   = '#000000' ;

$image_file   = 'idtemplate.png';

$image_file1    = 'personid.png';

      

//CUSTOMIZABLE: Define x-y coordinates for the Name Text to be written to idtemplate.png

$x_finalpos   = 500;

$y_finalpos   = 425;

  

//CUSTOMIZABLE: Define x-y coordinates for the ID number text to be written to template.png

//Note: Coordinates are dependent on the size of the image template

$x_finalpos1  = 500;

$y_finalpos1  = 525;

  

//Declare image file extensions in PNG format.

$mime_type           = 'image/png' ;

$extension           = '.png' ;

  

//Check for server GD support

if(!function_exists('ImageCreate'))

fatal_error('Error: Server does not support PHP image generation') ;

  

//Check font file availability

if(!is_readable($font_file)) {

fatal_error('Error: The server is missing the specified font.') ;

}

  

//Define font colors

$font_rgb = hex_to_rgb($font_color) ;

  

//Define the bounding box coordinates for name text using the Truefonttype font file specified       

$box = @ImageTTFBBox($font_size,0,$font_file,$name) ;

  

//Define the bounding box coordinates for ID number text using the Truefonttype specified.

$box1 = @ImageTTFBBox($font_size,0,$font_file,$idnumber) ;

  

//Define name width and height

$name_width = abs($box[2]-$box[0]);

$name_height = abs($box[5]-$box[3]);

  

//Define ID number width and height

$text_width1 = abs($box1[2]-$box1[0]);

$text_height1 = abs($box1[5]-$box1[3]);

  

//Create an image from ID template PNG and assign to $image variable

$image =  imagecreatefrompng($image_file);

  

//Create an image from person's picture ID PNG and assign it to $personid variable

$personid = imagecreatefrompng($image_file1);

  

//CUSTOMIZABLE: Merge the ID picture of the person to the ID template in a specific coordinates.

//You can read about imagecopymerge function manual here: http://php.net/manual/en/function.imagecopymerge.php

imagecopymerge($image, $personid, 717, 259, 0, 0, 253, 300, 100);

//Check if the server cannot create the image and displays error.

if(!$image || !$box || !$box1)

{

fatal_error('Error: The server could not create this image.') ;

}

  

//Allocate color of the image and then measure the image width

$font_color = ImageColorAllocate($image,$font_rgb['red'],$font_rgb['green'],$font_rgb['blue']) ;

$image_width = imagesx($image);

  

//Finalize the position of the name text on the generated image.

$put_text_x = $image_width - $name_width - ($image_width - $x_finalpos);

$put_text_y = $y_finalpos;

  

//Finalize the position of the ID number text on the generated image

$put_text_x1 = $image_width - $text_width1 - ($image_width - $x_finalpos1);

$put_text_y1 = $y_finalpos1;

  

// Write the NAME text to the image

imagettftext($image, $font_size, 0, $put_text_x,  $put_text_y, $font_color, $font_file, $name);

  

//Write the ID NUMBER text to the image

imagettftext($image, $font_size, 0, $put_text_x1,  $put_text_y1, $font_color, $font_file, $idnumber);

  

//Declare header content type in PNG

header('Content-type: ' . $mime_type) ;

  

//Output the generated PNG image with the text to the browser

imagepng($image) ;

  

//Destroy image to prevent memory leak and then exit.

ImageDestroy($image) ;

exit ;

/*

The FATAL error function will

attempt to create an image containing the error message given.

If this works, the image is sent to the browser. If not, an error

is logged, and passed back to the browser as a 500 code instead.

*/

function fatal_error($message)

{

// send an image

if(function_exists('ImageCreate'))

{

$width = ImageFontWidth(5) * strlen($message) + 10 ;

$height = ImageFontHeight(5) + 10 ;

if($image = ImageCreate($width,$height))

{

$background = ImageColorAllocate($image,255,255,255) ;

$text_color = ImageColorAllocate($image,0,0,0) ;

ImageString($image,5,5,5,$message,$text_color) ;   

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

imagePNG($image) ;

ImageDestroy($image) ;

exit;

}

}

// send 500 code

header("HTTP/1.0 500 Internal Server Error") ;

print($message) ;

exit ;

}

/*

Decode an HTML hex-code into an array of R,G, and B values.

Accepts these formats: (case insensitive) #ffffff, ffffff, #fff, fff

*/   

function hex_to_rgb($hex) {

// remove '#'

if(substr($hex,0,1) == '#')

$hex = substr($hex,1) ;

// expand short form ('fff') color to long form ('ffffff')

if(strlen($hex) == 3) {

$hex = substr($hex,0,1) . substr($hex,0,1) .

substr($hex,1,1) . substr($hex,1,1) .

substr($hex,2,1) . substr($hex,2,1) ;

}

if(strlen($hex) != 6)

fatal_error('Error: Invalid color "'.$hex.'"') ;

// convert from hexidecimal number systems

$rgb['red'] = hexdec(substr($hex,0,2)) ;

$rgb['green'] = hexdec(substr($hex,2,2)) ;

$rgb['blue'] = hexdec(substr($hex,4,2)) ;

return $rgb ;

}

?>



 
 
>>> More PHP Articles          >>> More By Codex-M
 

blog comments powered by Disqus
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: