Jump to content


Happy Holidays from Codecall!



Recent Topics

Recent Status Updates

  • Photo
      25 Dec
    MaheshKumar

    JER HR Consulting LLC, originally established in 1990 as James E. Rocco Associates, Inc., was created to provide quality compensation consulting services to non-profit organizations by offering a comprehensive suite of services that support an effective Total Rewards Strategy. Our team of specialists provides expert assistance that is tailored to the individual needs and challenges of each valued client. We work closely with Human Resources Departments, Chief Executive Officers and other sen...

View All Updates

Developed by TechBiz Xccelerator
Photo
- - - - -

PHP:Tutorial - Getting to know GD

php

  • Please log in to reply
9 replies to this topic

#1 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 03 December 2006 - 01:37 AM

Title: Create dynamic userbars with GD

Introduction:
Have you ever been on aim and received a message from one of your friends with a big long URL followed by something like "John%20Is%20Stupid." You know what ever it is, wont be worth your time, but you click on it anyway to find someone goofy looking holding a sign and on it printed in big bold letters “John Is Stupid.” Ever wonder how they work? Chances are the script takes advantage of the GD functions. In this tutorial you will learn many GD functions that you can use to generate images. The goal for this tutorial is for you to generate a dynamic user bar.

Here is a list of the functions used in this tutorial:
header()
http://us3.php.net/m...orallocate.php'>imagecolorallocate()
imagettfbbox()
imagesx()
abs()
imagettftext()
imagepng()
imagedestroy()

Solution:
The first thing you want to do is create the header type using the header function. Next you use the GD tools to create an image from a png file. In my case, I have userbar.png in the same directory as this script is in. The function imagecolorallocate creates a color using RGB (red-green-blue) format. The next three lines just set some basic information which isn’t that hard to understand. The last three lines to must of the work creating the image. The most important function here to pay attention to is imagettftext. The imagettftext requires 8 arguments which are the resource image, font size, the angle, x location, y location, font color, the actual font, and the string to be printed.

<?php
header('Content-type: image/png');
$im = imagecreatefrompng ("userbar.png");
$color = imagecolorallocate($im, 0, 0, 0);
$text = "test";
$font = 'font.ttf';
$size = 8;
imagettftext($im, $size, 0, 15, 12, $color, $font, $text);
imagepng($im);
imagedestroy($im);
?>


Now that we have GD generating an image, lets make it a little more complex. We’ve added the
$text = $_GET['text']; 
line to allow the user to enter a random string, and we have also added the
 $size = imagettfbbox($fontsize, 0, $font, $text);
$dx = (imagesx($im)) - (abs($size[2]-$size[0])) - 20;

Which calculate where to start printing the string on the image. The function imagettfbbox generates the length of the font string in pixels. If you were to use something like strlen($text) that would just return the number of characters in the string, which isn’t very usefull in this case. Next, we use the imagesx() function to determine the width of the image, we take that value and subtract the string length in pixels and subtract an extra 20 pixels to leave some room toward the end of the image.
<?php
header('Content-type: image/png');
$text = $_GET['text'];
$im = imagecreatefrompng ("userbar.png");
$color = imagecolorallocate($im, 0, 0, 0);
$font = 'font.ttf';
$fontsize = 6;
$size = imagettfbbox($fontsize, 0, $font, $text); //calculate the pixel of the string
$dx = (imagesx($im)) - (abs($size[2]-$size[0])) - 20; //calculate the location to start the text
imagettftext($im, $fontsize, 0, $dx, 13, $color, $font, $text);
imagepng($im);
imagedestroy($im);
?>


At this point you could call yourself done. However you could add some extra features such as make the font color vary with the user input. Adding a simple if statement will accomplish this.

<?php
header('Content-type: image/png');
$text = $_GET['text'];

$im = imagecreatefrompng ("userbar.png");

if($text == "ADMINISTRATOR"){ //if administrator
$color = imagecolorallocate($im, 255, 0, 0); //red
}
elseif($text == "MODERATOR"){ //if moderator
$color = imagecolorallocate($im, 0, 0, 255); //blue
}
elseif($text == "JUNKIE"){ //if junkie
$color = imagecolorallocate($im, 0, 0, 0); //black
}
else { //something else...
$color = imagecolorallocate($im, 0, 128, 0); //green
}

$font = 'font.ttf'; //font file
$fontsize = 6; //font size
$stringsize = imagettfbbox($fontsize, 0, $font, $text); //calculate the pixel of the string
$dx = (imagesx($im)) - (abs($stringsize[2]-$stringsize[0])) - 20; //calculate the location to start the text
imagettftext($im, $fontsize, 0, $dx, 13, $color, $font, $text);
imagepng($im);
imagedestroy($im);
?>


Finally you can save this script as generator.php and display it in forums by using the html tags.

<img src="http://www.yourdomain.com/generator.php?text=JUNKIE" />

This post was originally written for [noparse]johnciacia.com[/noparse] and may not be reused or reposted without consent from the author.

Attached Files


Edited by John, 04 January 2010 - 02:56 PM.

  • 2

#2 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 03 December 2006 - 02:28 AM

Here are two more scripts that take advantage of GD, I've posted these before but I figured i'll post them here to keep track of them.

Captcha Generator
<?php
function RandomStringGenerator($length){
global $string;
$pattern = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
if(empty($length)){
$length = "10";
}
for($i=0; $i<$length; $i++){
$string .= $pattern{rand(0,61)};
}

return $string;
}

function CaptchaGenerator(){
global $string;
RandomStringGenerator();
header("Content-type: image/png");
$im = @imagecreate(100, 50)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 255, 0, 0);
imagestring($im, 10, 5, 5, $string, $text_color);
imagepng($im);
imagedestroy($im);
}

CaptchaGenerator();
?>


Signature Rotator/Banner Rotator:

<?php

$folder = './';

$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';

$img = null;

if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}

if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);

if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}

if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}

?>


To add a border to text:
/**
* Writes the given text with a border into the image using TrueType fonts.
* @author John Ciacia < John@extreme-hq.com >
* @param image An image resource.
* @param size The font size.
* @param angle The angle in degrees to rotate the text.
* @param x Upper left corner of the text.
* @param y Lower left corner of the text.
* @param textcolor This is the color of the main text.
* @param strokecolor This is the color of the text border.
* @param fontfile The path to the TrueType font you wish to use.
* @param text The text string in UTF-8 encoding.
* @param px Number of pixels the text border will be.
* @return Returns an array with 8 elements representing four points making the bounding
* box of the text. The order of the points is lower left, lower right, upper right,
* upper left. The points are relative to the text regardless of the angle, so
* "upper left" means in the top left-hand corner when you see the text horizontally.
* @see http://us.php.net/ma...magettftext.php
* @see http://forum.codecall.net
* @see http://www.extreme-hq.com
*/
function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {

for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
$bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);

return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}
Usage:
$img = imagecreatefrompng("/home/john/Desktop/test.png");
$font_color = imagecolorallocate($img, 0, 0, 0);
$stroke_color = imagecolorallocate($img, 255, 0, 0);
$font = "/home/john/Desktop/ABSTRACT.TTF";
$txt = "This is a test..";
$px = 2;
imagettfstroketext($img, 10, 0, 10, 50, $font_color, $stroke_color, $font, $txt, $px);


Enjoy! :D

Edited by John, 04 May 2008 - 10:37 AM.

  • 0

#3 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 03 December 2006 - 07:31 AM

Nice Tutorial, very well done.
  • 0

#4 TcM

TcM

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 7,563 posts

Posted 03 December 2006 - 08:04 AM

:0 Im impressed ;) I wish I knew PHP
  • 0

#5 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 03 December 2006 - 10:54 AM

Thanks for the comments, ive added 2 more scripts to this section that you've already seen but also take advantage of GD so i figured they were worth showing :)
  • 0

#6 TcM

TcM

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 7,563 posts

Posted 04 December 2006 - 10:50 AM

I have a problem with the 1st tutorial.. I made this:-
<html>
<img src="http://localhost/generator.php?text=ADMINISTRATOR" />
</html>
Right? its localhost because I ran a Server on my PC to try this.. and it supports PHP but the image link is showing as broken.. any idea why?
I even tried to upload it to a hosting site that supports php.. still broken link...
  • 0

#7 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 04 December 2006 - 11:28 AM

I'm betting you do not have GD working or compiled into your system. Is it a Windows System?

Create a PHP file named phpinfo.php and put this in it:


<?php
phpinfo();
?>


Then goto http://localhost/phpinfo.php - this lists everything that your PHP can do. Search for GD.
  • 0

#8 TcM

TcM

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 7,563 posts

Posted 04 December 2006 - 12:02 PM

Well when I tried localhost/phpinfo.php nothing cameup.. perhaps its not configured correctly but then I tried it on a hosting site yes it is Enabled!!:-

gd
GD Support enabled
GD Version bundled (2.0.28 compatible)
FreeType Support enabled
FreeType Linkage with freetype
GIF Read Support enabled
GIF Create Support enabled
JPG Support enabled
PNG Support enabled
WBMP Support enabled
XBM Support enabled


I opened the PHP file generator.php ( on the hosting site )and it said:-

The image “http://tcm9669.9999m...m/generator.php” cannot be displayed, because it contains errors.


huh??
  • 0

#9 John

John

    CC Mentor

  • Moderator
  • 4,450 posts
  • Location:New York, NY

Posted 04 December 2006 - 02:55 PM

If your running this script on a linux server, i believe the font i included is called font.TTF not font.ttf
  • 0

#10 TcM

TcM

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 7,563 posts

Posted 04 December 2006 - 10:06 PM

Well the hosting site would not let me upload .tff just .TFF .. Dam them! Well never mind I just wanted to try it!! but still nice tut...
  • 0





Powered by binpress