A profile badge for a social site

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
pkearney06
Forum Newbie
Posts: 3
Joined: Fri Jul 18, 2008 7:43 am

A profile badge for a social site

Post by pkearney06 »

I was looking at my facebook the other day and they have a really neat little feature on there that allows you to create a profile badge which is basically an image with your facebook account information on it to be used on other websites or emails or the sort. It's a pretty neat little networking feature, or so it is in my opinion. Well, I took to making my own and I made quiet a bit of progress in about an hour. Luckily I already had a resizing script which made it EXTREMELY easy. So, here's what I got and I welcome what you'd like to see done, and criticism of course.

This is the backend scripting for php handling the image functions such as resizing, and placing and merging and so on.

Place this file in a file all its own. I called it createBadge.php but it doesn't matter what it's called so long as on the next page you change the include file.

Code: Select all

 
 
<?php
 
class createBadge {
 
    function load($filename) { //Load image file and convert to a readable state for php
      $image_info = getimagesize($filename); //Get image information
      $this->image_type = $image_info[2]; //Get image type
     
      //Cycles through image types
      if( $this->image_type == IMAGETYPE_JPEG ) {
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
         $this->image = imagecreatefrompng($filename);
      }
    }
    
    function save($filename, $image_type) { //Saves image to specified location default image type is beginning image type but can be changed
      //Cycles through image types
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename, 100);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image,$filename);
      } 
    }
    
    function output($image_type=IMAGETYPE_JPEG) { //Outputs image to be read through browser or html image tag, default output is jpeg
      //Cycles through image types
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image);        
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image);
      }   
    }
    
    function getWidth() { //Obtains image width
      return imagesx($this->image);
    }
    
    function getHeight() { //Obtains image height
      return imagesy($this->image);
    }
    
    function resizeToHeight($height) { //Resizes image to specified height and dynamic width
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
    }
    
    function resizeToWidth($width) { //Resizes image to specified width and dynamic height
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
    }
    
    function scale($scale) { //Resizes image to dynamic height and dynamic width by percent
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100; 
      $this->resize($width,$height);
    }
    
    function resize($width,$height) { //Resizes image to dynamic height and dynamic width by specific amount
      $new_image = imagecreatetruecolor($width, $height);
      imagesavealpha($new_image, true);
      imagealphablending($new_image, false);
      imagesavealpha($new_image,true);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
    }
    
    function badge($attExists=0){ //Default is no attributes
    
        $this->resizeToWidth(75); //Resizes profile picture to 75 width dynamic height
        
        if($attExists){ //If there is text other than just profile pictures
            $totalWidth = $this->getWidth() + 250;
            $totalHeight = $this->getHeight() + 20;
        } else {
            $totalWidth = $this->getWidth() + 50; //Sets totalWidth if no other text
            $totalHeight = $this->getHeight() + 20; //Sets totalHeight if no other text
        }
            
        //Start Create Profile Pic//
        $profile = imagecreatetruecolor($totalWidth, $totalHeight); //Creates blank canvas to add profile picture onto
        $nastyColor = imagecolorallocate($profile, 255, 0, 255); //Gives us a nasty color to fill the background with to make it transparent
        imagefill($profile, 0, 0, $nastyColor); //Fills background
        imagecopyresampled($profile, $this->image, 0, 0, 0, 0, $this->getWidth(), $this->getHeight(), $this->getWidth(), $this->getHeight()); //Add profile pic to blank canvas
        
        $cBackground = imagecolorclosest($profile, 255, 0, 255); //Important for transparency
        imagecolortransparent($profile, $cBackground); //Important for transparency
        //End Create Profile Pic//
    
        //Start create background//
        if($this->getHeight() <= 60){
            $totalHeight = 90; //Resets height to be a bit more suitable
            $im = imagecreatetruecolor($totalWidth, $totalHeight); //Create image with enough room for side panel, image, and padding
        } else {
            $im = imagecreatetruecolor($totalWidth, $totalHeight);
        }
    
        $border = imagecolorallocate($im, 0, 0, 0); //Set border color
        $padding_bg = imagecolorallocate($im, 255, 255, 255); //Set padding color
        $main_bg = imagecolorallocate($im, 230, 230, 240); //Set main background color
        $side_bg = imagecolorallocate($im, 70, 50, 160); //Set company name background color
        
        imagefill($im, 0, 0, $border); //Fills background
 
        imagefilledrectangle($im, 1, ($totalHeight) - 2, ($totalWidth) - 2, 1, $padding_bg); //Fills padding
    
        imagefilledrectangle($im, 4, ($totalHeight) - 6, ($totalWidth) - 6, 4, $main_bg); //Fills main color
        
        imagefilledrectangle($im, 1, ($totalHeight), 30, 1, $side_bg); //Adds company name background color
    
        //End Create Background//
        
        //Start Merge Profile Pic and BG//
        $setX = 38; //Sets profile picture x axis out enough to miss the 30 pixel wide side company name
        if($this->getHeight() < 100){
            $setY = ((imagesy($im)-imagesy($profile)) /2) + 10; //Sets profile picture y axis if height is under 100
        } else {
            $setY = ((imagesy($im)-imagesy($profile)) /2) + 10; //Sets profile picture y axis if height is over 100
        }
        
        imagecopymerge($im, $profile, $setX, $setY, 0, 0, imagesx($im), imagesy($profile), 100); //Adds profile to background
        //End Merge Profile Pic and BG//
        
        $this->image = $im;
    }
    
    function addCoName($txt){ //only supports up to 16 characters at the moment
    
        $face = "../tpl/fonts/BabelSans.ttf"; //Tells what font to use
    
        $im = $this->image; //Assigns php rendered image
        
        $white = imagecolorallocate($im, 255, 255, 255); //Declares font color
        
        if(strlen($txt) >= 10){
            if(strlen($txt) > 20){
                $txt = substr($txt, 0, 19);
            }
            $txt = substr($txt, 0, 9)."\n".substr($txt, 10, strlen($txt));
            
            $fontSize = imagettfbbox(10, 0, $face, $txt); //Gets font dimensions
        
            $fontHeight = $fontSize[4] - $fontSize[6]; //Gets total font height technically width but it will be rotated
        
            $centerFont = (($this->getHeight()) - $fontHeight) / 2; //Used to center the font
            
            imagettftext($im, 10, 90, 10, $fontHeight + $centerFont, $white, $face, $txt); //Adds font to image
            
        } else {
            $txt = $txt;
        
            $fontSize = imagettfbbox(12, 0, $face, $txt); //Gets font dimensions
            
            $fontHeight = $fontSize[4] - $fontSize[6]; //Gets total font height technically width but it will be rotated
        
            $centerFont = (($this->getHeight()) - $fontHeight) / 2; //Used to center the font
        
            imagettftext($im, 12, 90, 20, $fontHeight + $centerFont, $white, $face, $txt); //Adds font to image
        }
    }
    
    function addText($val, $type, $numAtt, $order){
    
        $face = "../tpl/fonts/BabelSans.ttf"; //Tells what font to use
    
        $im = $this->image; //Assigns php rendered image
        
        $labelC = imagecolorallocate($im, 100, 100, 100); //Declares label color
        $fontC = imagecolorallocate($im, 50, 50, 50); //Decalres font color
        
        $fontSize = imagettfbbox(10, 0, $face, $txt); //Gets font dimensions
        
        $top = ceil((imagesy($im)- 42) /2) + 6;
        
        if($order > 1){
            for($i=2;$i<=$order;$i++){
                $top = $top + 20;
            }
        }
        
        imagettftext($im, 10, 0, 120, $top, $labelC, $face, $type." :"); //Adds label to image
        imagettftext($im, 10, 0, 180, $top, $fontC, $face, $val); //Adds text to image
    }
};
 
$createBadge = new createBadge;
 
?>
 
 


This is a sort of mid end scripting (still backend scripting but I find it easier to use a hierarchy to keep it straight in my head) You can use the following code in two ways. Either as is so the browser outputs just the specific image or in an image tag (which will be explained in a moment) to be used in html.

Save this file in the same directory or be sure to change the include path

Code: Select all

 
 
<?php
 
header("Content-Type: image/png");
 
include("createBadge.php");
 
$load = $createBadge->load(/path/to/profile/image); //Loads Profile Image
$badge = $createBadge->badge(1); //Creates badge with a value of 1 meaning there will be things like names and emails...use 0 for just a profile picture
$addCoName = $createBadge->addCoName("The Company"); //Adds a company name to the left side written vertically
$name = $createBadge->addText("Patrick Kearney", "Name", 3, 1); //Adds a name to the badge
$email = $createBadge->addText("somename@somesite.com", "Email", 3, 2); //Adds a email to the badge
$birthday = $createBadge->addText("June 11, 1988", "Birthday", 3, 3); //Adds a birthday to the badge
$output = $createBadge->output(IMAGETYPE_PNG); //Outputs the image to the browser
 
//$save = $createBadge->save("/save/location"); Saves image to specific location
 
?>
 
 
Basically this file will create the badge, add a profile pic, add a name, email and birthday as well as a company name by the name of "The Company".

It's a pretty basic use. It will only output it to the browser for viewing (if you uncomment the $save value and change the directory it will save a file).

You can also do something to this affect to use this code through your html

Assuming that you saved the above midlevel script in a file named badge.php and this html is in the same directory:

Code: Select all

 
<img src="badge.php" border=0 />
 
This will give you a usable dynamic image throughout your website (If you use the save function this won't matter). You can also create the image dynamically instead of statically by changing the midlevel script to something like this:

Code: Select all

 
 
<?php
 
header("Content-Type: image/png");
 
include("createBadge.php");
 
$load = $createBadge->load($_GET['i']);
$badge = $createBadge->badge(1);
$addCoName = $createBadge->addCoName("The Company");
$name = $createBadge->addText($_GET['n'], "Name", 3, 1);
$email = $createBadge->addText($_GET['e'], "Email", 3, 2);
$birthday = $createBadge->addText($_GET['b'], "Birthday", 3, 3);
$output = $createBadge->output(IMAGETYPE_PNG);
 
//$save = $createBadge->save("/save/location");
 
?>
 
 
Then you can create your badge dynamically and use it in your html like this (Assuming the above file is saved as badge.php:

Code: Select all

 
 
<img src="badge.php?i=../profile/image&n=Patrick Kearney&e=somename@somesite.com&b=June 11, 1988" border=0 />
 
 
Of course you can easily change this to dynamically create your badge. I would love to get developers input (bearing in mind this was the quick version just thought I'd get it out there) about what I should add (or be added), what could be improved and if possible how.

The outcome comes to something to this effect:

Image
Last edited by pkearney06 on Fri Aug 29, 2008 7:43 pm, edited 1 time in total.
pkearney06
Forum Newbie
Posts: 3
Joined: Fri Jul 18, 2008 7:43 am

Re: A profile badge for a social site

Post by pkearney06 »

.: Bump :.

Any suggestions? You can't become a better programmer without constructive criticism.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: A profile badge for a social site

Post by JAB Creations »

In this particular forum I'm much more likely to ask for constructive criticism then to be able to give it however towards giving up on finding anything I could suggest improvement for something horrible wrong caught my eye: an email address.

Bots account for a huge percentage of web traffic and I highly recommend two things...

1.) Remove the email address from that post.

2.) Never under any circumstances use an unencrypted email address at the client even if you require a session/cookie/etc. Bots are now breaking through CAPTCHA and they will chew your email address up if you post it in the wrong spot.

Besides that I don't consider myself advanced enough to see anything else wrong here though I'm not exactly happy to see over 60 views but no one else mentioning what I am in this post. Ca-mon guys!

Also I personally find Facebook completely obnoxious...actually all of the social networking sites are but Facebook's app system tops my list of worst things ever.
pkearney06
Forum Newbie
Posts: 3
Joined: Fri Jul 18, 2008 7:43 am

Re: A profile badge for a social site

Post by pkearney06 »

Agreed on the email thing however it was simply an example. Most likely you would be using emails from a database through an encrypted source. The get method I used was merely to show how the badge worked, not the only way it could work. Beyond that, thanks for the reply.
andriecool
Forum Newbie
Posts: 1
Joined: Fri Oct 31, 2008 1:35 pm

Re: A profile badge for a social site

Post by andriecool »

hi pkearney06,

this is a great script, i've been looking eveywhere...

i tried to run this script on localhost (using winXP and wampserver 2.0c) it looks like this:

ImageImage

pretty good..!!

but, when i uploaded this script (i tried 2 different webserver) it looks like this

ImageImage

as you can see... some script doesnt work... do u know how to fix this error?

it seems that the background image failed.. or something else?
Post Reply