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;
}
?>

C++ MySQL Database Class

Comments 2 Standard
/**************
* File Name: database.cpp
* Author: Design1online.com, LLC
* Purpose: mysql database class
**************/
#include "database.h"

/**************
* Purpose: default constructor, initialize class values
* Precondition: none
* Postcondition: none
**************/
database::database()
{
 //initilize the mysql fields
 sock = NULL;
 row = NULL;
 result = NULL;
 field = NULL;          
}

/**************
* Purpose: connect to the appropriate database
* Precondition: host, database, user name and password
* Postcondition: connected to that database
**************/
int database::openConnection(char *host, char *db, char *user, char *pass)
{
 if (sock) //already connected to another database
 disconnect(); //disconnect from that one

 //initilize the socket
 sock = mysql_init(0);

 //something went wrong with the socket
 if (!sock)
 return ERR201;

 //try connecting to the database  
 if (!mysql_real_connect(sock, host, user, pass, db, 0, NULL, 0))
 return ERR202;

 //successfully connected to the database    
 return SUCCESS;  
}

/**************
* Purpose: disconnect from the database
* Precondition: none
* Postcondition: socket closed
**************/
bool database::disconnect()
{
 if (sock) //they have a socket open
 mysql_close(sock);

 //release result data
 free(); 

 //database disconnected
 return true;
}

/**************
* Purpose: free the results from the database query
* Precondition: none
* Postcondition: results no longer there
**************/
bool database::free()
{
 if (result)
 {
 mysql_free_result(result);
 return true;
 }

 return false;
}

/**************
* Purpose: return the approprite error message
* Precondition: error code
* Postcondition: string with the error returned
**************/
char *dberror(int errorcode)
{

 //display the appropriate error message for this error    
 switch(errorcode)
 {
 case SUCCESS: return "SUCCESS";
 break;

 case ERR201: return "201 SOCKET ERROR: SOCKET FAILURE";
 break;

 case ERR202: return "202 CONNECTION ERROR: CANNOT ACCESS THE SERVER";
 break;

 case ERR203: return "203 DATABASE ERROR: QUERY FAILED";
 break;
 }

 return NULL; //no error, return null
}

/**************
* Purpose: return the result set of the query
* Precondition: the query string
* Postcondition: result set returned (or null)
**************/
MYSQL_RES *database::query(char *query)
{        
 //query the database
 mysql_query(sock, query);

 //store the results
 result = mysql_store_result(sock);

 return result;

}

/**************
* Purpose: update the database no result returned
* Precondition: the query string
* Postcondition: false if failed, true if suceess
**************/
bool database::updateQuery(char *query)
{        
 if (!mysql_query(sock, query))
 return 0; //failed query
 else
 return 1; //successful query
}

/**************
* Purpose: return the result set of the query
* Precondition: the query string
* Postcondition: the FIRST result is returned (or null)
*                will not return multiple rows, only the first
**************/
char *database::stringQuery(char *query)
{
 //if old results exist, free them
 //free();

 //query the database
 mysql_query(sock,query);

 //store the results
 result = mysql_store_result(sock);

 if (!result)
 return NULL; //no results

 //fetch the row
 row = mysql_fetch_row(result);

 //store the result & convert it to a number
 char *stringResult = row[0];

 //free the results
 free();

 return stringResult;

}

/**************
* Purpose: return the result set of the query
* Precondition: the query string
* Postcondition: the FIRST result is returned (or null)
*                will not return multiple rows, only the first
**************/
int database::intQuery(char *query)
{        
 //query the database
 mysql_query(sock,query);

 //store the results
 result = mysql_store_result(sock);

 if (!result)
 return -1; //no results

 //fetch the row
 row = mysql_fetch_row(result);

 //store the result & convert it to a number
 int id = atoi(row[0]);

 //free the results
 free();

 return id; //return the id number

}

/**************
* Purpose: return the result set of the query
* Precondition: the query string
* Postcondition: the FIRST result is returned (or null)
*                will not return multiple rows, only the first
**************/
bool database::boolQuery(char *query)
{

 //query the database
 mysql_query(sock, query);

 //store the results
 result = mysql_store_result(sock);

 return (bool)row[0];

}

/**************
* File Name: database.h
* Author: jade@design1online.com
* Purpose: header file for database.cpp class
**************/
#ifndef DATABASE_H
#define DATABASE_H

#include "mysql/mysql.h"

/**************
* Database Error Definitions
**************/
#define SUCCESS 200
#define ERR201 201
#define ERR202 202
#define ERR203 203
#define MAX_QUERY_LEN 500

class database
{
 public:
 //class constructor
 database(); 

 //connection & disconnect
 int       openConnection(char *host, char *db, char *user, char *pass); //connect to the database
 bool      disconnect(); //disconnect from the database

 //querying
 MYSQL_RES *query(char *query); //return result set
 char      *stringQuery(char *query); //return string
 int       intQuery(char *query); //return an integer
 bool      boolQuery(char *query); //return a boolean
 bool      updateQuery(char *query); //updates, returns true if update went through

 //free the query results
 bool free();

 private:
 MYSQL *sock;
 MYSQL_RES *result;
 MYSQL_ROW row;
 MYSQL_FIELD *field;
 char *qbuf[MAX_QUERY_LEN];
};

char *dberror(int errorcode); //return a string for this error message

#endif

In order for this to work correctly you also need the libmysql.dll file in any of your compiled projects and you’ll also need to setup mysql.h header files to link them in during compilation.

Programming Challenge Main Page or Continue to Day 4