Create Dynamic Images With PHP/MySQL

posted by John Owen on August 5th, 2009, in PHP, Web Design | 2 Comments

You can view the demo of what we will be creating here: Dynamic Images
I will be using my local server to do this tutorial, first off with need to create some data to use in this tutorial. I have provided a MYSQL Query string for you to use. I am using PHP 5.3 and MySQL 3.2.0.1.

-- Table structure for table `people`
--
 
CREATE TABLE IF NOT EXISTS `people` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
 
--
-- Dumping data for table `people`
--
 
INSERT INTO `people` (`id`, `first_name`, `last_name`, `email`) VALUES
(1, 'Tim', 'Carpenter', 'tim@carpentercentral.com'),
(2, 'Joe', 'Woolen', 'joewoolen@gmail.com'),
(3, 'Harry', 'Melvis', 'hmelvis@live.com'),
(4, 'Jane', 'Suden', 'janes211@yahoo.com'),
(5, 'Sue', 'Baxter', 'suebax@hotmail.co.uk'),
(6, 'Jeremy', 'Yun', 'jerry@jerry123.com');

Summary

You will be retrieving an email from the database then getting the length of the email and inserting it into an image thats size is custom to the length of the text. This prevents email spiders from reading the email.

Step 1 – Connecting To The Database

Create a new file called “config.php” and put this code in it:

<?php
define('MYSQL_USER', 'root');
define('MYSQL_PASS', '');
define('MYSQL_DB', 'data_db');
define('MYSQL_HOST', 'localhost');
 
$dbc = @mysql_connect (MYSQL_HOST, MYSQL_USER, MYSQL_PASS) OR die('Could not connect to MySQL: ' . mysql_error() );
 
@mysql_select_db (MYSQL_DB) OR die('Could not select the database: ' . mysql_error() );
?>

Enter your details at MYSQL_USER/PASS/DB, you wont need to change localhost unless you know you need to change it.

Step 2 – Index.php

Create a new file called index.php with this code:

<?php include('config.php'); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dynamic Images</title>
</head>
 
<body>
</body>
</html>

This is our template. In the index file we will list the names and then you will be able to click the name and view their email.

Step 3 – Listing The Names

Before we delve into the actual image creation we need to list our names. Insert this PHP code between your two body tags (HERE).

<?php
	// Will select all fields except email from table 'poeple'. You can select all fields by using a * (eg. SELECT * FROM people)
	$query = "SELECT id,first_name,last_name FROM people";
	// Run the query & grab the result , if error it will display the error
	$result = mysql_query($query) or die('Mysql error: ' . mysql_error());
	// We now have all data in the result, to retrieve this we need to use the mysql_fetch_array in a while loop
?>
<h3>Names</h3>
<table width="300" border="0" cellspacing="5" cellpadding="5">
	<tr>
    	<td width="32">ID</td>
    	<td width="147">Name</td>
    	<td width="71"></td>
  	</tr>
<?php
	// the while loop will go though each row and display data from the coloumns
	// the view email link will link to a page called view_email.php with a $_GET function
	while ($row = mysql_fetch_array($result)) { ?>
		<tr>
    		<td width="32"><?php echo $row['id']; ?></td>
    		<td width="147"><?php echo $row['first_name'] . ' ' . $row['last_name']; // combines the first & last name to display full name ?></td>
    		<td width="71"><a href="view_email.php?id=<?php echo $row['id']; // links the ID to the view_email.php page ?>">View Email</a></td>
  		</tr>
	<?php } // in between the two PHP sections the code will go, this makes it easier to read?>
</table>

names

Step 4 – view_webcam.php

Create a new file and name it “view_webcam.php”, enter this code in.

<?php include('config.php'); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dynamic Images</title>
</head>
<body>
<?php
	//check if the $_GET variable 'id' isset, if it is run the image creation blabla
	if (isset($_GET['id'])) {
		// include the img.php file to create the email from the var id
		echo '<img src="img.php?id=' . $_GET['id'] . '">';
	} else {
		// If no var has been set tell the visitor
		echo 'No ID has been given.';	
	}
?>
</body>
</html>

Not much but it basically inserts an image with a link to a PHP script, the PHP script acts like a image by chaging the header content type to png.

Step 5- img.php

Create a new PHP file and name it img.php, this is the main part of out tutorial so i’ll explain a lot more :)

<?php
	// Check if the ?id= has been set if so continue
	if (isset($_GET['id'])) {
 
		// connect to the database
		include('config.php');
 
 
		// retrieves info from the row relating to the ID
		function retrieve_info($id) {
		//Build the query to retrieve the email, will retrieve the email by the ID
		$query = "SELECT * FROM people WHERE id='$id'";
		// Run the query and do any error stuff
		$result = mysql_query($query) or die('MySQL Error: ' . mysql_error());
		// Convert the data into an array
		$data = mysql_fetch_array($result);
		// Since this is a function we need to return the data.
		//
		return $data;
	}
 
		// CHANGE THESE VARIABLES
		// Replace path by your own font path
		$font = "sanford.tff";
		// Font size (reccomended do not change) (make divisible by 2 for better results)
		$font_size = 14;
 
 
		//set var
		$data = retrieve_info($_GET['id']);
		$email = $data['email'];
		// Count the amount of characters in the email
		$chars = strlen($email);
		// each character is about 14 pixels so lets width a bit more
		$extra = $font_size - 3;
		// calculate width by multiplying each character by the character width plus extraspace
		$width = ($chars * $extra);
		//height of image
		$height = $font_size + 10;
 
		// Create the acording to the calculated size of the text
		$im = imagecreate($width, $height);
 
		// Create some colors (B&W)
		$white = imagecolorallocate($im, 255, 255, 255);
		$black = imagecolorallocate($im, 0, 0, 0);
 
 
 
		// Add the text
		imagettftext($im, $font_size, 0, 5, ($height - 7), $black, $font, $email);
 
		// Set the content-type
		header('Content-type: image/png');
 
		// Using imagepng() results in clearer text compared with imagejpeg()
		imagepng($im);
		imagedestroy($im);
 
	} else {
		// if there is no $data variable then echo text
		echo 'no data avaliable to create image';
	}
?>

dynamicimage

To put it simply this script grabs the users ID name from the GET method using variables in the URL, it then calculates the size of the image by finding out the amounting of characters and multiplying them by the font size. On the white background we grab a font in the current directory to use and write the text of the email around the center of the image. Then it outputs the image, to make the browser read it as a image file we need to change the header. Thats what the header part of the script does.

If no $_GET var for the user ID is found then it will just echo an error.

Conclusion

If you want me to put up a demo just post a comment and i’ll put it up ASAP.
This method can be used to track visitors, give custom user images or an array of other things. Here are the files to download:
Dynamic Images PHP Files (Includes Font) (241)

2 Responses to “Create Dynamic Images With PHP/MySQL”

  1. Tony said...

    Can u please upload demo,

    thanks.

  2. John Owen said...

    Tony, sorry for the wait here is the demo: http://www.webmediamagazine.com/demo/dynamic-images/

Leave a Reply