Jump to content

Random Avatar Code nothing working


DeanWhitehouse

Recommended Posts

Ok, so i have decided to rewrite my random avatar code and has not worked at all., lol.

 

So here is my problem, when i first ran the code it caused a 500 internal server error, then i found that a function named random_check was causing this and further debugging showed that $avatar_count and $_SESSION['num']; are not defined.

 

So i have tried to fix it and cannot find why its not working, any help is appreciated.

 

<?php
/**
*Page to show a different avatar each time
*
*
*@package Avatar Randomness
*@author Dean Whitehouse (aka Blade280891) - deanwhitehouse6@hotmail.com - http://www.djw-designs.com - http://www.djw-webdesign.awardspace.com
*/

session_start();
    if(isset($_SESSION['random']))// check for the session that contains the random number then unset it.
    {
        unset($_SESSION['random']);
        /*
        Unset the session that stores the random image reference number, for more info;
        The php manual, http://uk.php.net/unset
        */
    }

    $_SESSION['random'] = Generate_Random();
    /*
    Generate a new number for the image reference number
    */

    if(!isset($_SESSION['num']))
    {
        $_SESSION['num'] = $_SESSION['random'];
    }
/*
Begin sessions, for more info visit either:
The php manual, http://uk.php.net/session
or my sites tutorial on using sessions to protect pages, http://djw-webdesign.awardspace.com/code.php?snippet=9
*/

$avatar_resize = 50; //The amount , in percent, to resize the avatar
/*
Stored the amount to resize the avatar by in a variable, for more info visit;
Php manual, http://uk3.php.net/language.variables
*/

/*
Uncomment these lines to change the image using set widths and heights, only un comment one to keep the image aspect ratio
$new_width = 128;//In pixels
$new_height =  264;//In pixels
*/

$avatars = array
(
    "http://spearbang.awardspace.com/Sonic-animated.gif",
    "http://spearbang.awardspace.com/Tails-salutes.gif",
    "http://spearbang.awardspace.com/Sonic-and-Shadow-transform.gif",
    "http://spearbang.awardspace.com/Knuckles2.gif"
);
/*
Store the avatars in an array, for more info on arrays visit;
The php manual, http://uk3.php.net/array
or my site, http://djw-webdesign.awardspace.com/code.php?snippet=8
*/

$avatar_count = count($avatars);

###########################################
################- Functions -####################
###########################################

/**
*Function to generate the avatar image.
*
*Selects an image, resizes the image and then sends the image and headers to the browser
*@return string image
*/
function Generate_Image()
{
    return Resize_Image($avatars[$_SESSION['random']]);
}

/**
*Function to resize the image.
*
*Resizes the inputted image
*@param string image url
*@return string new image url
*/
function Resize_Image($image)
{
    $current_image = $image;

    $image_type = Get_Image_Type($current_image);

    echo $image_type;
    //http://uk.php.net/switch
    switch($image_type)
    {
        case "jpg" || "jpeg":
            $new_image = imagecreatefromjpeg($current_image);
            break;
        case "gif":
            $new_image = imagecreatefromgif($current_image);
            break;
        case "png":
            $new_image = imagecreatefrompng($current_image);
            break;
        case "bmp":
            $new_image = imagecreatefromwbmp($current_image);
            break;
        default:
            $new_image = imagecreatefromgif($current_image);
    }

    // Capture the original size of the uploaded image
    list($width,$height) = getimagesize($new_image);

    if(isset($new_width) || isset($new_height))
    {
        if(isset($new_width) && !isset($new_height) || $new_height < 1)
        {
            $new_width = ($new_width < 1 ? $width: $new_width);
            $new_height = ($height / $width) * $new_width;
        }
        elseif(isset($new_height) && !isset($new_width) || $new_width < 1)
        {
            $new_height = ($new_height < 1 ? $height: $new_height);
            $new_width = ($height / $width) * $new_height;
        }
        else
        {
            $new_height = ($new_height < 1 ? $height: $new_height);
            $new_width = ($new_width < 1 ? $width: $new_width);
        }
    }
    else
    {
        $new_height = ($height / 100) * $avatar_resize;
        $new_width = ($width / 100) * $avatar_resize;
    }
    echo $widht." - ".$new_width."<br>".$height." - ".$new_hieght;
    $tmp_image = imagecreatetruecolor($new_width,$new_height);

    imagecopyresampled($tmp_image,$new_image,0,0,0,0,$new_width,$new_height,$width,$height);

    return $tmp_image;
}

/**
*Function to get the image type
*
*Inputted image url is exploded to find the image extension
*@param string image url
*@return string image extension
*/
function Get_Image_Type($image)
{
    $image_type = explode(".",$image);
    $image_type = $image_type[count($image_type)];
    return $image_type;
}

/**
*Function to generate the send the page headers
*
*Sends the correct page headers to the browser
*/
function Send_Page_Headers($image_type = "")
{
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header("content-type: image/gif");//Image type
}

/**
*Function to generate the check if the image was shown previosuly
*
*checks the session to find out what image was sent last
*@return bool true if new image is different from last image, else runs in a loop
*/
function random_check()
{        
    if($_SESSION['num'] == $_SESSION['random'])
    {
        $_SESSION['random'] = mt_rand(0,$avatar_count);
        random_check();
    }
    return true;
}    

/**
*Function to generate a random number between 0 and the amount of avatars stored
*
*uses mt_rand to generate a random number
*@return integer random number
*/
function Generate_Random()
{    
    return mt_rand(0,$avatar_count);
    /*
    Generate a random number between 0 and the amount of avatar images stored in the array
    For more information about mt_rand visit; 
    http://uk.php.net/mt_rand
    */
}

###########################################
###############-- Display Image --##################
###########################################


//if(random_check())
//{
    //Send_Page_Headers();
    echo (Generate_Image());
//}
$_SESSION['num'] = $_SESSION['random'];
?>

Edit:

This is the output

- 0

-

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/www/djw-webdesign.awardspace.com/examples/avatar2.php on line 137

 

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/www/djw-webdesign.awardspace.com/examples/avatar2.php on line 139

Link to comment
Share on other sites

Do $new_height and $new_width echo out valid dimensions?

 

Here are some solutions other people found with a similar problem drupal.

 

Check the permissions on the folder where the images are uploaded.

 

Hope these will work, sorry I don't have a definite answer, good luck  ;)

 

 

Link to comment
Share on other sites

Surely i don't need to pass them to the function via an argument?

 

You sure do, it is all about the "scope". You could store them in session or make them global.

 

<?php
function test() {
    echo $a; // should echo nothing
}

function test2($a) {
    echo $a; // should echo out $a
}

function test3() {
    global $a;
    echo $a; // should echo out $a
}

global $a;

$a = "test<br />";

test();
test2($a);
test3();

?>

 

Hope that helps you to understand better.

 

EDIT:

For more information google or look in the PHP Manual for "Variable Scope" it should do a better explanation than I can give.

Link to comment
Share on other sites

Ok i have made this half-way solution, just to make sure the code works.

 

<?php
error_reporting(E_ALL);
/**
*Page to show a different avatar each time
*
*
*@package Avatar Randomness
*@author Dean Whitehouse (aka Blade280891) - deanwhitehouse6@hotmail.com - http://www.djw-designs.com - http://www.djw-webdesign.awardspace.com
*/

session_start();
/*
Begin sessions, for more info visit either:
The php manual, http://uk.php.net/session
or my sites tutorial on using sessions to protect pages, http://djw-webdesign.awardspace.com/code.php?snippet=9
*/

$avatar_resize = 50; //The amount , in percent, to resize the avatar
/*
Stored the amount to resize the avatar by in a variable, for more info visit;
Php manual, http://uk3.php.net/language.variables
*/

/*
Uncomment these lines to change the image using set widths and heights, only un comment one to keep the image aspect ratio
$new_width = 128;//In pixels
$new_height =  264;//In pixels
*/

$avatars = array
(
"../images/djw_logo.jpg",
"http://spearbang.awardspace.com/Sonic-animated.gif",
"http://spearbang.awardspace.com/Tails-salutes.gif",
"http://spearbang.awardspace.com/Sonic-and-Shadow-transform.gif",
"http://spearbang.awardspace.com/Knuckles2.gif"
);
/*
Store the avatars in an array, for more info on arrays visit;
The php manual, http://uk3.php.net/array
or my site, http://djw-webdesign.awardspace.com/code.php?snippet=8
*/

$avatar_count = count($avatars);

###########################################
################- Functions -####################
###########################################

/**
*Function to generate the avatar image.
*
*Selects an image, resizes the image and then sends the image and headers to the browser
*@return string image
*/
function Generate_Image($avatars)
{
//print_r($_SESSION);
//print_r($avatars);
if(isset($_SESSION['random']))// check for the session that contains the random number then unset it.
{
	unset($_SESSION['random']);
	/*
	Unset the session that stores the random image reference number, for more info;
	The php manual, http://uk.php.net/unset
	*/
}

$_SESSION['random'] = mt_rand(0,(count($avatars) - 1));
/*
Generate a new number for the image reference number
*/

if(!isset($_SESSION['num']))
{
	$_SESSION['num'] = $_SESSION['random'];
}

return Resize_Image($avatars[$_SESSION['random']]);
}

/**
*Function to resize the image.
*
*Resizes the inputted image
*@param string image url
*@return string new image url
*/
function Resize_Image($image)
{
$current_image = $image;
$avatar_resize = 100;
$image_type = Get_Image_Type($current_image);

//echo $image_type;
//http://uk.php.net/switch
switch($image_type)
{
	case "jpg":
		$new_image = imagecreatefromjpeg($current_image);
		break;
	case "jpeg":
		$new_image = imagecreatefromjpeg($current_image);
		break;
	case "gif":
		$new_image = imagecreatefromgif($current_image);
		break;
	case "png":
		$new_image = imagecreatefrompng($current_image);
		break;
	case "bmp":
		$new_image = imagecreatefromwbmp($current_image);
		break;
	default:
		$new_image = imagecreatefromgif($current_image);
}

// Capture the original size of the uploaded image
list($width,$height) = getimagesize($current_image);

if(isset($new_width) || isset($new_height))
{
	if(isset($new_width) && !isset($new_height) || $new_height < 1)
	{
		$new_width = ($new_width < 1 ? $width: $new_width);
		$new_height = ($height / $width) * $new_width;
	}
	elseif(isset($new_height) && !isset($new_width) || $new_width < 1)
	{
		$new_height = ($new_height < 1 ? $height: $new_height);
		$new_width = ($height / $width) * $new_height;
	}
	else
	{
		$new_height = ($new_height < 1 ? $height: $new_height);
		$new_width = ($new_width < 1 ? $width: $new_width);
	}
}
else
{
	$new_height = ($height / 100) * $avatar_resize;
	$new_width = ($width / 100) * $avatar_resize;
}
//echo $width." - ".$new_width."<br>".$height." - ".$new_height;
$tmp_image = imagecreatetruecolor($new_width,$new_height);

imagecopyresampled($tmp_image,$new_image,0,0,0,0,$new_width,$new_height,$width,$height);
switch($image_type)
{
	case "jpg":
		return imagejpeg($tmp_image);
		break;
	case "jpeg":
		return imagejpeg($tmp_image);
		break;
	case "gif":
		return imagegif($tmp_image);
		break;
	case "png":
		return imagepng($tmp_image);
		break;
	case "bmp":
		return imagewbmp($tmp_image);
		break;  
	default:
		return imagegif($tmp_image);
}
}

/**
*Function to get the image type
*
*Inputted image url is exploded to find the image extension
*@param string image url
*@return string image extension
*/
function Get_Image_Type($image)
{
$image_type = explode(".",$image);
$image_type = $image_type[(count($image_type) - 1)];
return $image_type;
}

/**
*Function to generate the send the page headers
*
*Sends the correct page headers to the browser
*/
function Send_Page_Headers($image_type = "")
{
//header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
//header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("content-type: image/gif");//Image type
}

/**
*Function to generate the check if the image was shown previosuly
*
*checks the session to find out what image was sent last
*@return bool true if new image is different from last image, else runs in a loop
*/
function random_check($avatar_count)
{		
if($_SESSION['num'] == $_SESSION['random'])
{
	$_SESSION['random'] = mt_rand(0,($avatar_count -1));
	random_check($avatar_count);
}
return true;
}	

/**
*Function to generate a random number between 0 and the amount of avatars stored
*
*uses mt_rand to generate a random number
*@return integer random number
*/
function Generate_Random()
{	
return mt_rand(0,$avatar_count);
/*
Generate a random number between 0 and the amount of avatar images stored in the array
For more information about mt_rand visit; 
http://uk.php.net/mt_rand
*/
}

###########################################
###############-- Display Image --##################
###########################################


if(random_check($avatar_count))
{
Send_Page_Headers();
(Generate_Image($avatars));
}
$_SESSION['num'] = $_SESSION['random'];
?>

 

But now i have a problem that animated files don't play animations, i assume this is due to the image being recreated?

Link to comment
Share on other sites

You may want to look at the first exampled at the GD -> imagecreatefromgif Man Page.

 

imagecreatefromgif

frank at huddler dot com

05-Jan-2009 11:11

I wrote two alternate versions of ZeBadger's is_ani() function, for determining if a gif file is animated

 

Original:

http://us.php.net/manual/en/function.imagecreatefromgif.php#59787

 

The first alternative version is just as memory intensive as the original, and more CPU intensive, but far simpler:

 

<?php
function is_ani($filename) {
    return (bool)preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', file_get_contents($filename));
}
?>

 

The second alternative is about as CPU intensive as the original function, but uses less memory (and may also result in less disk activity)

 

<?php
function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C)
   
    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2)
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches);
   
    fclose($fh);
    return $count > 1;
}
?>

 

Hopefully that helps you out.

 

 

EDIT:

I do not think it will. What version of GD are you running (you can find out via phpinfo)

Link to comment
Share on other sites

Ok still got the problem, but here is a working version using OOP

 

<?php
/**
*Page to show a different avatar each time
*
*
*@package Avatar Randomness
*@author Dean Whitehouse (aka Blade280891) - deanwhitehouse6@hotmail.com - http://www.djw-designs.com - http://www.djw-webdesign.awardspace.com
*/

session_start();
/*
Begin sessions, for more info visit either:
The php manual, http://uk.php.net/session
or my sites tutorial on using sessions to protect pages, http://djw-webdesign.awardspace.com/code.php?snippet=9
*/

class Avatar
{
public $avatar_resize = 150;//The amount , in percent, to resize the avatar
/*
Uncomment these lines to change the image using set widths and heights, only un comment one to keep the image aspect ratio
public $new_width = 128;//In pixels
public $new_height =  264;//In pixels
*/

public $avatars = array
						(
							"http://spearbang.awardspace.com/Sonic-animated.gif",
							"http://spearbang.awardspace.com/Tails-salutes.gif",
							"http://spearbang.awardspace.com/Sonic-and-Shadow-transform.gif",
							"http://spearbang.awardspace.com/Knuckles2.gif"
						);
/*
Store the avatars in an array, for more info on arrays visit;
The php manual, http://uk3.php.net/array
or my site, http://djw-webdesign.awardspace.com/code.php?snippet=8
*/

public $avatar_count;

function __construct()
{
	$this->avatar_count = count($this->avatars) - 1;
	if(isset($_SESSION['random']))// check for the session that contains the random number then unset it.
	{
		unset($_SESSION['random']);
		/*
		Unset the session that stores the random image reference number, for more info;
		The php manual, http://uk.php.net/unset
		*/
	}

	$_SESSION['random'] = mt_rand(0, $this->avatar_count);
	/*
	Generate a new number for the image reference number
	*/

	if(!isset($_SESSION['num']))
	{
		$_SESSION['num'] = $_SESSION['random'];
	}
}

/**
*Function to generate the avatar image.
*
*Selects an image, resizes the image and then sends the image and headers to the browser
*@return string image
*/
function Generate_Image()
{	
	return self::Resize_Image($this->avatars[$_SESSION['random']]);
}	


/**
*Function to resize the image.
*
*Resizes the inputted image
*@param string image url
*@return string new image url
*/
function Resize_Image($image)
{
	$current_image = $image;

	$image_type = self::Get_Image_Type($current_image);

	//http://uk.php.net/switch
	switch($image_type)
	{
		case "jpg":
			$new_image = imagecreatefromjpeg($current_image);
			break;
		case "jpeg":
			$new_image = imagecreatefromjpeg($current_image);
			break;
		case "gif":
			$new_image = imagecreatefromgif($current_image);
			break;
		case "png":
			$new_image = imagecreatefrompng($current_image);
			break;
		case "bmp":
			$new_image = imagecreatefromwbmp($current_image);
			break;
		default:
			$new_image = imagecreatefromgif($current_image);
	}

	// Capture the original size of the uploaded image
	list($width,$height) = getimagesize($current_image);

	if(isset($this->new_width) || isset($this->new_height))
	{
		if(isset($this->new_width) && !isset($this->new_height) || $this->new_height < 1)
		{
			$this->new_width = ($this->new_width < 1 ? $width: $this->new_width);
			$this->new_height = ($height / $width) * $this->new_width;
		}
		elseif(isset($this->new_height) && !isset($this->new_width) || $this->new_width < 1)
		{
			$this->new_height = ($this->new_height < 1 ? $height: $this->new_height);
			$this->new_width = ($height / $width) * $this->new_height;
		}
		else
		{
			$this->new_height = ($this->new_height < 1 ? $height: $this->new_height);
			$this->new_width = ($this->new_width < 1 ? $width: $this->new_width);
		}
	}
	else
	{
		$this->new_height = ($height / 100) * $this->avatar_resize;
		$this->new_width = ($width / 100) * $this->avatar_resize;
	}

	$tmp_image = imagecreatetruecolor($this->new_width,$this->new_height);

	imagecopyresampled($tmp_image,$new_image,0,0,0,0,$this->new_width,$this->new_height,$width,$height);
	switch($image_type)
	{
		case "jpg":
			return imagejpeg($tmp_image);
			break;
		case "jpeg":
			return imagejpeg($tmp_image);
			break;
		case "gif":
			return imagegif($tmp_image);
			break;
		case "png":
			return imagepng($tmp_image);
			break;
		case "bmp":
			return imagewbmp($tmp_image);
			break;  
		default:
			return imagegif($tmp_image);
	}
}

/**
*Function to get the image type
*
*Inputted image url is exploded to find the image extension
*@param string image url
*@return string image extension
*/
function Get_Image_Type($image)
{
	$image_type = explode(".",$image);
	$image_type = $image_type[$this->avatar_count];
	return $image_type;
}

/**
*Function to generate the send the page headers
*
*Sends the correct page headers to the browser
*/
function Send_Page_Headers()
{
	//header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	//header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header("content-type: image/gif");//Image type
}

/**
*Function to generate the check if the image was shown previosuly
*
*checks the session to find out what image was sent last
*@return bool true if new image is different from last image, else runs in a loop
*/
function random_check()
{		
	if($_SESSION['num'] == $_SESSION['random'])
	{
		$_SESSION['random'] = mt_rand(0,$this->avatar_count);
		self::random_check();
	}
	return true;
}	
}

###########################################
###############-- Display Image --##################
###########################################
$avatar = new avatar;

if($avatar->random_check())
{
$avatar->Send_Page_Headers();
$avatar->Generate_Image();
}
$_SESSION['num'] = $_SESSION['random'];
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.