PHP Tutorial: Dynamically Colored Images, Overlays & Transparencies

Comments 4 Standard

So this one isn’t really a tutorial but it gives you a good idea how you’d go about changing the colors of pictures dynamically. To get the big picture on how you might use this try a working version that I created loosely based off the script below. This works great for changing the color of pets/items, etc without having to make 3 gazillion copies of them and spend hours in a graphic program like Photoshop. Instead you create an array of hex colors, slap a loop around this script and voila, you now have your item in the 10 different colors of your choosing. You have to have PHP compiled with GD support to run this script.

<?php
/*************
* Filename: index.php
* Purpose: change the base color of an image
* Author: design1online.com | games for girls
*************/

//fix the IE problems of not reloading the newest version of the image
header("Expires: Mon, 14 Jul 1789 12:30:00 GMT");    // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

//The files must be .pngs with transparent backgrounds
//The .png file itself must be saved in INDEXED color mode otherwise this won't work

$basecolor = 'basecolor.png'; //color of the horses coat, must be an all white image for colors to display properly
$outline = 'lines.png'; //outline of the horse
$percent = 0.75; //percentage to scale the image up or down 1 = 100%, 0.5 = 50% smaller, etc
$id = 123; //id of the picture you're creating -- usually this would correspond to the key of the record
$destfile = 'horse' . $id .'.jpg'; //creates a picture of this horse under this id number

// Get new dimensions
list($width, $height) = getimagesize($basecolor);
$new_width = $width * $percent;
$new_height = $height * $percent;

//the color we want to change it to
$htmlcolor = $_POST['htmlcolor'];

if (!$htmlcolor) //default color
 $htmlcolor = cccccc; //gray

//break the color into its RGB values
$red = hexdec(substr($htmlcolor, 0, 2));
$green = hexdec(substr($htmlcolor, 2, 2));
$blue = hexdec(substr($htmlcolor, 4, 2));

//for your reference
echo "Color is: $red | $green | $blue<br>";

//load the image you're going to change the color of
$image_p = @imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefrompng($basecolor);
imagecolorset($image, 0, $red, $green, $blue);
imagealphablending($image_p, false);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagesavealpha($image_p, true);

//recreate the image, overlaying the outline on the colored base
$image = imagecreatefrompng($outline);
imagealphablending($image_p, true);
imagesavealpha($image_p, true);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

//create the .png image and you're done
imagepng($image_p, $destfile);

//form so you can change from color to color with the push of a button
echo "<form action=\"index.php?id=" . rand() . "\" method=\"post\">";
echo "<center>";
echo "<img src=\"$destfile?fool="; //this is so older versions of IE won't cache the image
print md5(time());
echo "HTML color code: <input type=\"text\" name=\"htmlcolor\" value=\"". $_POST['htmlcolor'] . "\" \>";
echo "<br />";
echo "<input type=\"submit\" name=\"submit\" value=\"Change Color\" \><br />";
echo "</center>";
echo "</form>";
?>

Download the two images I used for this script basecolor.png (will look blank when you click on the link because this is a white image) and lines.png, right click on the links and save as. Simply put them in the same place as this .php file, run the file and watch the magic happen.

PHP Functions: Wiggle, Wobble, Squibble & Swipswap

Leave a comment Standard

Here are a few fun functions for word games, word scrambling and just plain word craziness.

<?php
/***********
* Purpose: move a certain letter to a certain position
* Precondition: word, letter to move, position to move it to
* Postcondition: word has been re-arranged
***********/
function wiggle($word, $letter, $position = 0)
{
 $word = str_replace(" ", "_", $word);

 if ($start = strpos($word, $letter))
 {
 $array = array_merge(str_split(substr($word, 0, $start)), str_split(substr($word, $start+1, strlen($word))));

 for ($i = 0; $i < strlen($word); $i++)
 {
 if ($i != $position)
 $final .= $array[$i];
 else
 $final .= $letter . $array[$i];
 }

 return str_replace("_", " ", $final);
 }
 else
 return; //letter wasn't found
}

/***********
* Purpose: move the letter at a certain position to a new position
* Precondition: word, position to move from, position to move to
* Postcondition: letter has moved from start to end position
***********/
function wobble($word, $start, $position = 0)
{
 $word = str_replace(" ", "_", $word);
 $start -= 1;

 $array = array_merge(str_split(substr($word, 0, $start)), str_split(substr($word, $start+1, strlen($word))));

 for ($i = 0; $i < strlen($word); $i++)
 {
 if ($i != $position)
 $final .= $array[$i];
 else
 $final .= substr($word, $start, 1) . $array[$i];
 }

 return str_replace("_", " ", $final);
}

/***********
* Purpose: move letters from this position and on to the beginning of the word
* Precondition: word, position to start from
* Postcondition: words from start to strlen($word) are not at the beginning of the word
***********/
function jiggle($word, $start)
{
 return substr($word, $start, strlen($word)-$start) . substr($word, 0, $start);
}

/***********
* Purpose: replace all $letters in the word with $replace
* Precondition: word, letter you want replaced, letter to replace it with
* Postcondition: word has been re-arranged
***********/
function swipswap($word, $letter, $replace)
{
 return str_replace($letter, $replace, $word);
}

/***********
* Purpose: every $length move the following $number of letters to the beginning of the word
* Precondition: word, lengh between squiggles, number of letters to move
* Postcondition: word has been re-arranged
***********/
function squiggle($word, $length = 1, $number = 2)
{

 if ($length >= strlen($word))
 $word = strrev($word);
 else
 {

 for ($i = 0; $i < strlen($word); $i++)
 {
 if ($i % $length)
 $word = substr($word, $i, $number) . substr($word, 0, $i) . substr($word, $i+$number, strlen($word));

 } //end for

 }//end else

 return $word;
}

//test it out!
echo wiggle("Hey Johnny 21", "e", 6);
echo "<br/>";
echo wobble("Hey Johnny 21", 3, 6);
echo "<br/>";
echo jiggle("Hey Johnny 21", 3);
echo "<br/>";
echo squiggle("Hey Johnny 21", 2, 2);
echo "<br/>";
echo swipswap("Hey Johnny 21", "n", "d");
?>

PHP Tutorial: Dynamically Create an Email Address in CPanel

Comment 1 Standard

This assumes you have cPanel and permission to run the /scripts/addpop command. You’ll need to write functions for validateUsername, validatePassword, and usernameExists or you can click on the links for each of those and use mine 🙂

<?php
function createEmail($username, $password)
{
if (!$username || !$password)
   return "Username missing.";
if (!$password)
   return "Password missing.";
if (!validateUsername($username)) //do your validation on the formatting, write this yourself...
  return "Invalid username, please try again.";
if (!validatePassword($password)) //do your validation on the formatting, length & strength, write this yourself...
  return "Invalid password, please try again.";
//check to see if this email address is already taken
if (usernameExists($username)) //write this yourself...
   return "This username already exists. Please select another one.";
//run the command
shell_exec ("/scripts/addpop " .  escapeshellcmd($username) . " " . escapeshellcmd($password))
return "Your email address has been created!";
}
?>

Mario AI Competition

Leave a comment Standard

Create your own Mario Artificial Intelligence game controller and win cash for your efforts! The top AI controller will be revealed at the IEEE 2009 Conference and has a nice prize of $500. Deadline is August 18th!

Get more details via their site: http://julian.togelius.com/mariocompetition2009/index.php

MSSQL Tutorial: Delete All But 1 Duplicate Records

Leave a comment Standard

declare @id int, @total int

/* SELECT COUNT OF POTENTIAL DUPLICATES */
select id, count(id) from [tablename]
where [parameters] group by [column name]

/* LOOP TO CLEAN UP THE DUPLICATES */
declare aff_crsr cursor LOCAL static for
select id, count(id) from [tablename]
where [parameters] group by id

open loop_crsr
fetch from loop_crsr into @id, @total

while @@fetch_status = 0 begin
print cast(@id as varchar) + ‘ – ‘ + cast(@total as varchar) + ‘ – ‘ + cast((@total – 1) as varchar)

delete top (@total-1) from [tablename] where id=@id and [parameters]

fetch from loop_crsr into @id, @total

PHP Tutorial: Mixing HEX Colors

Comment 1 Standard
<?php
/****************
* Purpose: mix two colors together
* Precondition: two colors in hex RGB format
* Postcondition: a single color returned that's the combo of the two
****************/
function mixcolors($color1, $color2)
{

  $c1_p1 = hexdec(substr($color1, 0, 2));
  $c1_p2 = hexdec(substr($color1, 2, 2));
  $c1_p3 = hexdec(substr($color1, 4, 2));

  $c2_p1 = hexdec(substr($color2, 0, 2));
  $c2_p2 = hexdec(substr($color2, 2, 2));
  $c2_p3 = hexdec(substr($color2, 4, 2));

  $m_p1 = sprintf('%02x', (round(($c1_p1 + $c2_p1)/2)));
  $m_p2 = sprintf('%02x', (round(($c1_p2 + $c2_p2)/2)));
  $m_p3 = sprintf('%02x', (round(($c1_p3 + $c2_p3)/2)));

 return    $m_p1 . $m_p2 . $m_p3;
}
?>