Category Archives: Image Handling

Upload Image and Create Thumbnail PHP Script

This is a PHP script that i wrote which receives an image from front end and uploads it, creates a thumbnail and returns both the master and thumb image info as JSON. I’ve pumped it with comments which should explain what the code does. This scripts works with the frontend code to use AJAX to upload image.

<?php
/*
  Copyright PHP Scripts 4U 2012
  Author: Sam Deering
*/


$error = $filename = $filesize = $fileloc = $thumb_name = '';
$fileElementName = 'image-upload';
$img_base_dir = "../img/uploaded/";

define ("MAX_SIZE","2000");  //define a maxim size for the uploaded images

// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","350");
define ("HEIGHT","150");

if(!empty($_FILES[$fileElementName]['error']))
{
    switch($_FILES[$fileElementName]['error'])
    {
        case '1':
            $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            break;
        case '2':
            $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            break;
        case '3':
            $error = 'The uploaded file was only partially uploaded';
            break;
        case '4':
            $error = 'No file was uploaded.';
            break;

        case '6':
            $error = 'Missing a temporary folder';
            break;
        case '7':
            $error = 'Failed to write file to disk';
            break;
        case '8':
            $error = 'File upload stopped by extension';
            break;
        case '999':
        default:
            $error = 'No error code avaiable';
    }
}
elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none')
{
    $error = 'No file was uploaded..';
}
else
{
    //save master image to temp folder, name it using a temp name
    //resize and save thumb image, name it using the same temp name as master

    //this is the function that will create the thumbnail image from the uploaded image
    //the resize will be done considering the width and height defined, but without deforming the image
    function make_thumb($img_name,$filename,$new_w,$new_h)
    {
        //get image extension.
        $ext=getExtension($img_name);
        //creates the new image using the appropriate function from gd library
        if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
          $src_img=imagecreatefromjpeg($img_name);

          if(!strcmp("png",$ext))
          $src_img=imagecreatefrompng($img_name);

          //gets the dimmensions of the image
        $old_x=imageSX($src_img);
        $old_y=imageSY($src_img);

        //next we will calculate the new dimmensions for the thumbnail image
        //the next steps will be taken:
        //  1. calculate the ratio by dividing the old dimmensions with the new ones
        //  2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
        //      and the height will be calculated so the image ratio will not change
        //  3. otherwise we will use the height ratio for the image
        // as a result, only one of the dimmensions will be from the fixed ones
        $ratio1=$old_x/$new_w;
        $ratio2=$old_y/$new_h;
        if($ratio1>$ratio2)
        {
          $thumb_w=$new_w;
          $thumb_h=$old_y/$ratio1;
        }
        else
        {
          $thumb_h=$new_h;
          $thumb_w=$old_x/$ratio2;
        }

        // we create a new image with the new dimmensions
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

        // resize the big image to the new created one
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

        // output the created image to the file. Now we will have the thumbnail into the file named by $filename
        if(!strcmp("png",$ext))
          imagepng($dst_img,$filename);
        else
          imagejpeg($dst_img,$filename);

          //destroys source and destination images.
        imagedestroy($dst_img);
        imagedestroy($src_img);
    }

       // This function reads the extension of the file.
       // It is used to determine if the file is an image by checking the extension.
       function getExtension($str)
       {
           $i = strrpos($str,".");
           if (!$i) { return ""; }
           $l = strlen($str) - $i;
           $ext = substr($str,$i+1,$l);
           return $ext;
       }

        //reads the name of the file the user submitted for uploading
       $image=$_FILES[$fileElementName]['name'];

    // if it is not empty
    if ($image)
    {
        // get the original name of the file from the clients machine
        $filename = stripslashes($_FILES[$fileElementName]['name']);

        // get the extension of the file in a lower case format
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        // if it is not a known extension, we will suppose it is an error, print an error message
        //and will not upload the file, otherwise we continue
        if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "png"))
        {
            $error .= 'Unknown extension!';
            $errors=1;
        }
        else
        {
            // get the size of the image in bytes
            // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
            //the uploaded file was stored on the server
            $size=getimagesize($_FILES[$fileElementName]['tmp_name']);
            $sizekb=filesize($_FILES[$fileElementName]['tmp_name']);

            //compare the size with the maxim size we defined and print error if bigger
            if ($sizekb > MAX_SIZE*1024)
            {
                $error .= 'You have exceeded the size limit!';
                $errors=1;
            }
            else {

            //we will give an unique name, for example the time in unix time format
            $image_name=time();

            //the new name will be containing the full path where will be stored (images folder)
            $master_name= $img_base_dir . 'temp/masters/' . $image_name . '.' .$extension;
            $copied = copy($_FILES[$fileElementName]['tmp_name'], $master_name);

            //we verify if the image has been uploaded, and print error instead
            if (!$copied)
            {
                $error .= 'Copy unsuccessfull!';
                $errors=1;
            }
            else
            {
                // the new thumbnail image will be placed in images/thumbs/ folder
                $thumb_name= $img_base_dir . 'temp/thumbs/'.$image_name .'_350.'.$extension;
                // call the function that will create the thumbnail. The function will get as parameters
                //the image name, the thumbnail name and the width and height desired for the thumbnail
                $thumb=make_thumb($master_name,$thumb_name,WIDTH,HEIGHT);
            }}
        }
    }


      //--------- END SECOND SCRIPT --------------------------------------------------------------------

      //return variables to javascript
      $filename = $_FILES[$fileElementName]['name'];
      $filesize = $sizekb;
      $fileloc = $thumb_name;
      //for security reason, we force to remove all uploaded file
      @unlink($_FILES[$fileElementName]);

      //image dimensions
      $masterWH = getimagesize($master_name);
      $masterW = $masterWH[0];
      $masterH = $masterWH[1];
      $thumbWH = getimagesize($thumb_name);
      $thumbW = $thumbWH[0];
      $thumbH = $thumbWH[1];
    }

    $ret = array(
        "master" => array(
            "orig_name" => $filename,
            "img_src" => str_replace("../", "", $master_name),
            "size" => round((filesize($master_name)/1000), 0) . 'kb',
            'h' => $masterH,
            'w' => $masterW
        ),
        "thumb" => array(
            "img_src" => str_replace("../", "", $thumb_name), //tweak return path of img
            "size" => round((filesize($thumb_name)/1000), 0) . 'kb',
            'h' => $thumbH,
            'w' => $thumbW
        )
    );

    if ($error !== "")
    {
        $ret["error"] = $error;
    }

    echo json_encode($ret);

?>

PHP for Directory Listing Script

Back in 2008 we released the original version of this directory listing script, this is the updated version which resolves a number of known issues with the previous version.The PHP Directory Listing Script is a highly configurable script which generates a well formed table, listing the contents of a specified directory and sub-directories. The script displays images for certain file types with the ability to generate thumbnails to preview image files.The PHP Directory Listing Script requires PHP, Javascript and GD2 for thumbnail generation.

 

<?php
/*
Directory Listing Script - Version 3
====================================
Script Author: Ash Young <ash@evoluted.net> / www.evoluted.net

REQUIREMENTS
============
This script requires PHP and GD2 if you wish to use the
thumbnail functionality.

INSTRUCTIONS
============
1) Unzip all files
2) Edit this file, making sure everything is setup as required.
3) Upload to server

CONFIGURATION
=============
Edit the variables in this section to make the script work as
you require.

Include URL - If you are including this script in another file,
please define the URL to the Directory Listing script (relative
from the host)
*/

$includeurl = false;

/*
Start Directory - To list the files contained within the current
directory enter '.', otherwise enter the path to the directory
you wish to list. The path must be relative to the current
directory and cannot be above the location of index.php within the
directory structure.
*/

$startdir = '.';

/*
Show Thumbnails? - Set to true if you wish to use the
scripts auto-thumbnail generation capabilities.
This requires that GD2 is installed.
*/

$showthumbnails = true;

/*
Memory Limit - The image processor that creates the thumbnails
may require more memory than defined in your PHP.INI file for
larger images. If a file is too large, the image processor will
fail and not generate thumbs. If you require more memory,
define the amount (in megabytes) below
*/

$memorylimit = false; // Integer

/*
Show Directories - Do you want to make subdirectories available?
If not set this to false
*/

$showdirs = true;

/*
Force downloads - Do you want to force people to download the files
rather than viewing them in their browser?
*/

$forcedownloads = false;

/*
Hide Files - If you wish to hide certain files or directories
then enter their details here. The values entered are matched
against the file/directory names. If any part of the name
matches what is entered below then it is not shown.
*/

$hide = array(
'dlf',
'index.php',
'Thumbs',
'.htaccess',
'.htpasswd'
);

/* Only Display Files With Extension... - if you only wish the user
to be able to view files with certain extensions, add those extensions
to the following array. If the array is commented out, all file
types will be displayed.
*/

/*$showtypes = array(
'jpg',
'png',
'gif',
'zip',
'txt'
);*/


/*
Show index files - if an index file is found in a directory
to you want to display that rather than the listing output
from this script?
*/

$displayindex = false;

/*
Allow uploads? - If enabled users will be able to upload
files to any viewable directory. You should really only enable
this if the area this script is in is already password protected.
*/

$allowuploads = false;

/* Upload Types - If you are allowing uploads but only want
users to be able to upload file with specific extensions,
you can specify these extensions below. All other file
types will be rejected. Comment out this array to allow
all file types to be uploaded.
*/

/*$uploadtypes = array(
'zip',
'gif',
'doc',
'png'
);*/


/*
Overwrite files - If a user uploads a file with the same
name as an existing file do you want the existing file
to be overwritten?
*/

$overwrite = false;

/*
Index files - The follow array contains all the index files
that will be used if $displayindex (above) is set to true.
Feel free to add, delete or alter these
*/


$indexfiles = array (
'index.html',
'index.htm',
'default.htm',
'default.html'
);

/*
File Icons - If you want to add your own special file icons use
this section below. Each entry relates to the extension of the
given file, in the form <extension> => <filename>.
These files must be located within the dlf directory.
*/

$filetypes = array (
'png' => 'jpg.gif',
'jpeg' => 'jpg.gif',
'bmp' => 'jpg.gif',
'jpg' => 'jpg.gif',
'gif' => 'gif.gif',
'zip' => 'archive.png',
'rar' => 'archive.png',
'exe' => 'exe.gif',
'setup' => 'setup.gif',
'txt' => 'text.png',
'htm' => 'html.gif',
'html' => 'html.gif',
'fla' => 'fla.gif',
'swf' => 'swf.gif',
'xls' => 'xls.gif',
'doc' => 'doc.gif',
'sig' => 'sig.gif',
'fh10' => 'fh10.gif',
'pdf' => 'pdf.gif',
'psd' => 'psd.gif',
'rm' => 'real.gif',
'mpg' => 'video.gif',
'mpeg' => 'video.gif',
'mov' => 'video2.gif',
'avi' => 'video.gif',
'eps' => 'eps.gif',
'gz' => 'archive.png',
'asc' => 'sig.gif',
);

/*
That's it! You are now ready to upload this script to the server.

Only edit what is below this line if you are sure that you know what you
are doing!
*/


if($includeurl)
{
$includeurl = preg_replace("/^\//", "${1}", $includeurl);
if(substr($includeurl, strrpos($includeurl, '/')) != '/') $includeurl.='/';
}

error_reporting(0);
if(!function_exists('imagecreatetruecolor')) $showthumbnails = false;
if($startdir) $startdir = preg_replace("/^\//", "${1}", $startdir);
$leadon = $startdir;
if($leadon=='.') $leadon = '';
if((substr($leadon, -1, 1)!='/') &amp;&amp; $leadon!='') $leadon = $leadon . '/';
$startdir = $leadon;

if($_GET['dir']) {
//check this is okay.

if(substr($_GET['dir'], -1, 1)!='/') {
$_GET['dir'] = strip_tags($_GET['dir']) . '/';
}

$dirok = true;
$dirnames = split('/', strip_tags($_GET['dir']));
for($di=0; $di<sizeof($dirnames); $di++) {

if($di<(sizeof($dirnames)-2)) {
$dotdotdir = $dotdotdir . $dirnames[$di] . '/';
}

if($dirnames[$di] == '..') {
$dirok = false;
}
}

if(substr($_GET['dir'], 0, 1)=='/') {
$dirok = false;
}

if($dirok) {
$leadon = $leadon . strip_tags($_GET['dir']);
}
}

if($_GET['download'] &amp;&amp; $forcedownloads) {
$file = str_replace('/', '', $_GET['download']);
$file = str_replace('..', '', $file);

if(file_exists($includeurl . $leadon . $file)) {
header("Content-type: application/x-download");
header("Content-Length: ".filesize($includeurl . $leadon . $file));
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($includeurl . $leadon . $file);
die();
}
die();
}

if($allowuploads &amp;&amp; $_FILES['file']) {
$upload = true;
if(!$overwrite) {
if(file_exists($leadon.$_FILES['file']['name'])) {
$upload = false;
}
}

if($uploadtypes)
{
if(!in_array(substr($_FILES['file']['name'], strpos($_FILES['file']['name'], '.')+1, strlen($_FILES['file']['name'])), $uploadtypes))
{
$upload = false;
$uploaderror = "<strong>ERROR: </strong> You may only upload files of type ";
$i = 1;
foreach($uploadtypes as $k => $v)
{
if($i == sizeof($uploadtypes) &amp;&amp; sizeof($uploadtypes) != 1) $uploaderror.= ' and ';
else if($i != 1) $uploaderror.= ', ';

$uploaderror.= '.'.strtoupper($v);

$i++;
}
}
}

if($upload) {
move_uploaded_file($_FILES['file']['tmp_name'], $includeurl.$leadon . $_FILES['file']['name']);
}
}

$opendir = $includeurl.$leadon;
if(!$leadon) $opendir = '.';
if(!file_exists($opendir)) {
$opendir = '.';
$leadon = $startdir;
}

clearstatcache();
if ($handle = opendir($opendir)) {
while (false !== ($file = readdir($handle))) {
//first see if this file is required in the listing
if ($file == "." || $file == "..")  continue;
$discard = false;
for($hi=0;$hi<sizeof($hide);$hi++) {
if(strpos($file, $hide[$hi])!==false) {
$discard = true;
}
}

if($discard) continue;
if (@filetype($includeurl.$leadon.$file) == "dir") {
if(!$showdirs) continue;

$n++;
if($_GET['sort']=="date") {
$key = @filemtime($includeurl.$leadon.$file) . ".$n";
}
else {
$key = $n;
}
$dirs[$key] = $file . "/";
}
else {
$n++;
if($_GET['sort']=="date") {
$key = @filemtime($includeurl.$leadon.$file) . ".$n";
}
elseif($_GET['sort']=="size") {
$key = @filesize($includeurl.$leadon.$file) . ".$n";
}
else {
$key = $n;
}

if($showtypes &amp;&amp; !in_array(substr($file, strpos($file, '.')+1, strlen($file)), $showtypes)) unset($file);
if($file) $files[$key] = $file;

if($displayindex) {
if(in_array(strtolower($file), $indexfiles)) {
header("Location: $leadon$file");
die();
}
}
}
}
closedir($handle);
}

//sort our files
if($_GET['sort']=="date") {
@ksort($dirs, SORT_NUMERIC);
@ksort($files, SORT_NUMERIC);
}
elseif($_GET['sort']=="size") {
@natcasesort($dirs);
@ksort($files, SORT_NUMERIC);
}
else {
@natcasesort($dirs);
@natcasesort($files);
}

//order correctly
if($_GET['order']=="desc" &amp;&amp; $_GET['sort']!="size") {$dirs = @array_reverse($dirs);}
if($_GET['order']=="desc") {$files = @array_reverse($files);}
$dirs = @array_values($dirs); $files = @array_values($files);


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Directory Listing of <?php echo str_replace('\', '', dirname(strip_tags($_SERVER['PHP_SELF']))).'/'.$leadon;?></title>
<link rel="stylesheet" type="text/css" href="<?php echo $includeurl; ?>dlf/styles.css" />
<?php
if($showthumbnails) {
?>
<script language="javascript" type="text/javascript">
<!--
function o(n, i) {
document.images['
thumb'+n].src = '<?php echo $includeurl; ?>dlf/i.php?f='+i<?php if($memorylimit!==false) echo "+'&amp;ml=".$memorylimit."'"; ?>;

}

function f(n) {
document.images['thumb'+n].src = 'dlf/trans.gif';
}
//-->
</script>
<?php
}
?>
</head>
<body>
<div id="container">
<h1>Directory Listing of <?php echo str_replace('\', '', dirname(strip_tags($_SERVER['PHP_SELF']))).'/'.$leadon;?></h1>
<div id="breadcrumbs"> <a href="<?php echo strip_tags($_SERVER['PHP_SELF']);?>">home</a>
<?php
$breadcrumbs = split('/', str_replace($startdir, '', $leadon));
if(($bsize = sizeof($breadcrumbs))>0) {
$sofar = '';
for($bi=0;$bi<($bsize-1);$bi++) {
$sofar = $sofar . $breadcrumbs[$bi] . '/';
echo ' &amp;gt; <a href="'.strip_tags($_SERVER['PHP_SELF']).'?dir='.strip_tags($sofar).'">'.$breadcrumbs[$bi].'</a>';
}
}

$baseurl = strip_tags($_SERVER['PHP_SELF']) . '?dir='.strip_tags($_GET['dir']) . '&amp;amp;';
$fileurl = 'sort=name&amp;amp;order=asc';
$sizeurl = 'sort=size&amp;amp;order=asc';
$dateurl = 'sort=date&amp;amp;order=asc';

switch ($_GET['sort']) {
case 'name':
if($_GET['order']=='asc') $fileurl = 'sort=name&amp;amp;order=desc';
break;
case 'size':
if($_GET['order']=='asc') $sizeurl = 'sort=size&amp;amp;order=desc';
break;

case 'date':
if($_GET['order']=='asc') $dateurl = 'sort=date&amp;amp;order=desc';
break;
default:
$fileurl = 'sort=name&amp;amp;order=desc';
break;
}
?>
</div>
<div id="listingcontainer">
<div id="listingheader">
<div id="headerfile"><a href="<?php echo $baseurl . $fileurl;?>">File</a></div>
<div id="headersize"><a href="<?php echo $baseurl . $sizeurl;?>">Size</a></div>
<div id="headermodified"><a href="<?php echo $baseurl . $dateurl;?>">Last Modified</a></div>
</div>
<div id="listing">
<?php
$class = 'b';
if($dirok) {
?>
<div><a href="<?php echo strip_tags($_SERVER['PHP_SELF']).'?dir='.urlencode($dotdotdir);?>"><img src="<?php echo $includeurl; ?>dlf/dirup.png" alt="Folder" /><strong>..</strong> <em>&amp;nbsp;</em>&amp;nbsp;</a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}
$arsize = sizeof($dirs);
for($i=0;$i<$arsize;$i++) {
?>
<div><a href="<?php echo strip_tags($_SERVER['PHP_SELF']).'?dir='.urlencode(str_replace($startdir,'',$leadon).$dirs[$i]);?>"><img src="<?php echo $includeurl; ?>dlf/folder.png" alt="<?php echo $dirs[$i];?>" /><strong><?php echo $dirs[$i];?></strong> <em>-</em> <?php echo date ("M d Y h:i:s A", filemtime($includeurl.$leadon.$dirs[$i]));?></a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}

$arsize = sizeof($files);
for($i=0;$i<$arsize;$i++) {
$icon = 'unknown.png';
$ext = strtolower(substr($files[$i], strrpos($files[$i], '.')+1));
$supportedimages = array('gif', 'png', 'jpeg', 'jpg');
$thumb = '';

if($showthumbnails &amp;&amp; in_array($ext, $supportedimages)) {
$thumb = '<span><img src="dlf/trans.gif" alt="'.$files[$i].'" name="thumb'.$i.'" /></span>';
$thumb2 = ' onmouseover="o('.$i.', \''.urlencode($leadon . $files[$i]).'\');" onmouseout="f('.$i.');"';

}

if($filetypes[$ext]) {
$icon = $filetypes[$ext];
}

$filename = $files[$i];
if(strlen($filename)>43) {
$filename = substr($files[$i], 0, 40) . '...';
}

$fileurl = $includeurl . $leadon . $files[$i];
if($forcedownloads) {
$fileurl = $_SESSION['PHP_SELF'] . '?dir=' . urlencode(str_replace($startdir,'',$leadon)) . '&amp;download=' . urlencode($files[$i]);
}

?>
<div><a href="<?php echo $fileurl;?>"<?php echo $thumb2;?>><img src="<?php echo $includeurl; ?>dlf/<?php echo $icon;?>" alt="<?php echo $files[$i];?>" /><strong><?php echo $filename;?></strong> <em><?php echo round(filesize($includeurl.$leadon.$files[$i])/1024);?>KB</em> <?php echo date ("M d Y h:i:s A", filemtime($includeurl.$leadon.$files[$i]));?><?php echo $thumb;?></a></div>
<?php
if($class=='b') $class='w';
else $class = 'b';
}
?></div>
<?php
if($allowuploads) {
$phpallowuploads = (bool) ini_get('file_uploads');
$phpmaxsize = ini_get('upload_max_filesize');
$phpmaxsize = trim($phpmaxsize);
$last = strtolower($phpmaxsize{strlen($phpmaxsize)-1});
switch($last) {
case 'g':
$phpmaxsize *= 1024;
case 'm':
$phpmaxsize *= 1024;
}

?>
<div id="upload">
<div id="uploadtitle">
<strong>File Upload</strong> (Max Filesize: <?php echo $phpmaxsize;?>KB)

<?php if($uploaderror) echo '<div>'.$uploaderror.'</div>'; ?>
</div>
<div id="uploadcontent">
<?php
if($phpallowuploads) {
?>
<form method="post" action="<?php echo strip_tags($_SERVER['PHP_SELF']);?>?dir=<?php echo urlencode(str_replace($startdir,'',$leadon));?>" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
<?php
}
else {
?>
File uploads are disabled in your php.ini file. Please enable them.
<?php
}
?>
</div>

</div>
<?php
}
?>
</div>
</div>
<div id="copy">Directory Listing Script &amp;copy;2008 Evoluted, <a href="http://www.evoluted.net/">Web Design Sheffield</a>.</div>
</body>
</html>

PHP image rotator script

Simple Image Rotator that rotates images in a web page.This free rotater allows rotating images on web pages at a predefined time interval.They can be located at any different directories.Option to set the size and speed of rotation.Just Download for free and Use it.Web Rotater can be used for Image Slide Shows.Simple To Use.

<script language="javascript">
imgAr = new Array();
<?php
$file = "$hm/HIR/images.txt";

$lines = file($file);
$count = count($lines);
//echo("Toal Images to rotate".$count."<br>");

$i=0;
$k=0;

foreach ($lines as $line_num => $line)
{
if($k==0)
{
$k=$k+1;
$firstPos = strpos($line,'"');
$secPos = strpos($line,'"',($firstPos+1));
$width = substr($line,$firstPos+1,($secPos-$firstPos)-1);

$firstPos1 = strpos($line,'"',($secPos+1));
$secPos1 = strpos($line,'"',($firstPos1+1));
$height = substr($line,$firstPos1+1,($secPos1-$firstPos1)-1);

$firstPos2 = strpos($line,'"',($secPos1+1));
$secPos2 = strpos($line,'"',($firstPos2+1));
$speed = substr($line,$firstPos2+1,($secPos2-$firstPos2)-1);
}
else
{
//echo $line;
$firstPos = strpos($line,'"');
$secPos = strpos($line,'"',($firstPos+1));
//echo "=======================$firPos-$secPos<br>";
$img[$i] = substr($line,$firstPos+1,($secPos-$firstPos)-1);
$imh = $img[$i];
print "imgAr.push(\"$imh\" );";
//echo $img[$i]."<br>";
$i=$i+1;
}
}
?>
</script>

<script language="javascript">
var k = 0;
var wid12 = <?php echo($width); ?>;
var hig12 = <?php echo($height); ?>;

if (document.images)
{
var rImg = new Array();
for (var i=0; i<imgAr.length; i++)
{
rImg[i] = new Image(wid12,hig12);
rImg[i].src = imgAr[i];
}
}

function rotater()
{
//var ssd = imgAr[k];
//document["test"].src = ssd;
document["test"].src = rImg[k].src;

if( k < (imgAr.length-1))
{
k= k+1;
}
else
{
k = 0;
}

rTimer = setTimeout('rotater()', <?php echo($speed); ?> );

}
</script>

<table align=center cellpading=0 cellspacing=0 border=0>
<tr><td>
<img width="<?php echo($width); ?>"  height="<?php echo($height); ?>" name=test src="<?php echo($img[0]); ?>">
</td></tr><tr align=right><td>
<a href="http://www.hscripts.com" style="font-size: 8px; color:green; text-decoration:none;">HIR</a>
</td></tr></table>

<script language="javascript">
rotater();
</script>

PHP Date and Time to Image Swap Tame

Event manager script is a complete solution for all your event needs. Our event manager tool gives you facility to create event on your website. The events can be showed on your website to keep update your website users. Events are shown according.

 

<?php

 /*****************************************************
 ** Title........: Voting Class
 ** Filename.....: voting.class.inc.php
 ** Author.......: Ralf Stadtaus
 ** Homepage.....: http://www.stadtaus.com/
 ** Contact......: http://www.stadtaus.com/forum/
 ** Version......: 0.3
 ** Notes........:
 ** Last changed.: 2004-03-18
 ** Last change..: IP check
 *****************************************************/


 /*****************************************************
 **
 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
 ** OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
 ** LIMITED   TO  THE WARRANTIES  OF  MERCHANTABILITY,
 ** FITNESS    FOR    A    PARTICULAR    PURPOSE   AND
 ** NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR
 ** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 ** OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
 ** CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF
 ** OR  IN  CONNECTION WITH THE SOFTWARE OR THE USE OR
 ** OTHER DEALINGS IN THE SOFTWARE.
 **
 *****************************************************/






 class Voting
 {




 /*****************************************************
 ** Log all downloads - new line for each download
 *****************************************************/

 function log($log_path, $vote_name, $intern_value, $extern_value)
 {

 $log_content = array(

 get_ip(),                       // (Required) IP address of the remote host
 @gethostbyaddr(get_ip()),       // (Required) Name of the remote host
 date("Y-m-d (H:i)", mktime()),  // (Required) Date of the download (in international ISO format)
 mktime(),                       // (Required) Date of the download (in Unix timestamp)
 $vote_name,                     // (Required) Internal vote name
 $intern_value,                  // (Required) Internal voting option number
 $extern_value,                  // (Optional) Actual voting option name
 getenv('HTTP_REFERER'),         // (Optional) Referring URL
 getenv('HTTP_USER_AGENT'),      // (Optional) User agent

 );



 $log_content = join(' - ', $log_content);

 debug_mode($log_content, 'Log Entry');

 if ($logfile = fopen($log_path, 'a')) {
 flock($logfile, 2);
 if (fputs($logfile, $log_content . "\n")) {
 fclose($logfile);
 return 1;
 }
 fclose($logfile);
 }

 }




 /*****************************************************
 ** Content of the count file
 *****************************************************/

 function count_content($file_name, $download_number, $first_download, $last_download)
 {
 $log_content = array(
 $file_name,                                 /* Name of the download file */
 $download_number + 1,                       /* Adds 1 to current number of downloads */
 date("Y-m-d (H:i)", $first_download),       /* Date of the first download (in international ISO format) */
 date("Y-m-d (H:i)", $last_download),        /* Date of the last download (in international ISO format) */
 $first_download,                            /* Date of the first download in Unix timestamp */
 $last_download                              /* Date of the last download in Unix timestamp */

 );


 $log_content = join(' - ', $log_content);


 return $log_content;
 }




 /*****************************************************
 ** Reads the numbers of downloads and calculates the
 ** new download number.
 *****************************************************/

 function count($log_path, $download_path, $file_name)
 {
 unset($log_template_content);

 $query_file_name  = trim($file_name);
 $current_time     = mktime();


 if (is_file($log_path)) {

 $count_file_content   = file($log_path);
 $log_template_content = array();


 while(list($key, $line) = each($count_file_content))
 {
 $line = trim($line);

 if (!empty($line)) {
 $data             = explode(' - ', $line);
 $stored_file_name = trim($data[0]);


 if (trim($data[0]) == trim($file_name)) {

 $download_number = trim($data[1]);
 $first_download  = trim($data[4]);
 $last_download   = mktime();


 $log_template_content_temp = $this->count_content($stored_file_name, $download_number, $first_download, $last_download);
 $log_template_content[]    = $log_template_content_temp;

 debug_mode($log_template_content_temp, 'Replace Entry');

 unset($log_template_content_temp);

 $check = 'true';

 } else {
 $log_template_content[] = $line;
 }
 }
 }

 if (!isset($check) or $check != 'true') {
 $log_template_content_temp = $this->count_content($query_file_name, 0, $current_time, $current_time);
 $log_template_content[]    = $log_template_content_temp;

 debug_mode($log_template_content_temp, 'New Entry');

 unset($log_template_content_temp);
 }


 $new_file_content = join("\n", $log_template_content);

 if ($logfile = fopen($log_path, 'w+')) {
 flock($logfile, 2);
 fputs($logfile, $new_file_content);
 fclose($logfile);
 }
 } else {

 $log_template_content = $this->count_content($query_file_name, 0, mktime(), mktime());

 debug_mode($log_template_content, 'First Entry');

 if ($logfile = fopen($log_path, 'a')) {
 flock($logfile, 2);
 fputs  ($logfile, $log_template_content . "\n");
 fclose ($logfile);
 }

 }
 }




 /*****************************************************
 ** Get number of votes
 *****************************************************/

 function get_vote_result($log_path, $vote_name)
 {

 if (is_file($log_path)) {

 $count_file_content   = file($log_path);
 $log_template_content = array();
 $rating               = 0;


 while(list($key, $line) = each($count_file_content))
 {
 $line = trim($line);

 if (!empty($line)) {

 $data = explode(' - ', $line);
 $intern_value = trim($data[5]);

 if ($vote_name == trim($data[4])) {

 if (isset($option[$intern_value])) {
 $option[$intern_value]++;
 } else {
 $option[$intern_value] = 1;
 }


 $rating_value = trim($data[6]);

 if (is_numeric($rating_value)) {
 $rating += $rating_value;
 }

 $check = 'true';

 }
 }
 }

 if (isset($check) and $check == 'true') {
 return array('voting' => $option, 'rating' => $rating);
 }
 }
 }




 /*****************************************************
 ** Check last voting time by ip address
 *****************************************************/

 function check_ip_address($log_path, $name, $time, $ip)
 {

 if (is_file($log_path)) {

 $count_file_content   = file($log_path);
 $log_template_content = array();


 while(list($key, $line) = each($count_file_content))
 {
 $line = trim($line);

 if (!empty($line)) {

 $data = explode(' - ', $line);
 // echo trim($data[4]);

 if ($name == trim($data[4]) and trim($data[3]) >= $time and $ip == trim($data[0])) {
 return trim($data[0]);
 }
 }
 }
 }
 }



 } // End of class
?>

&amp;nbsp;

Multifunction Image Handler PHP Script Navigation

This script is a very easy to use multifunction image handler script for your weather web site. The caching feature makes it the perfect solution to gracefully “hot link” an image from another web site. Note: Please use common courtesy… get permission to use the image you will download and display.

 

 

<pre><?php
/*
PHP script by Mike Challis, www.642weather.com/weather
Multifunction Image Handler PHP Script - multifunction-image-handler.php
Script available at: http://www.642weather.com/weather/scripts.php
Contact Mike: http://www.642weather.com/weather/contact_us.php
Live Demo: http://www.642weather.com/weather/scripts-image-handler.php#IHdemo
Version: 1.99.2  01-Feb-2010

See change log for complete history:
http://www.642weather.com/weather/scripts-history.php
Version: 1.99.2  01-Feb-2010  - fix: some servers return 203 instead of 200 OK

You are free to use and modify the code for your own non-commercial use

This php code provided "as is", and Long Beach Weather (Michael Challis)
disclaims any and all warranties, whether express or implied, including
(without limitation) any implied warranties of merchantability or
fitness for a particular purpose. Warning: always make sure you have permission
to "hot link" images from other web sites. This script is designed to be a more
graceful way to link other site's images, asking for their permission,
and excluding their content from your copyright is absolutely recommended.

License:
    This work is licensed under a
    CREATIVE COMMONS ATTRIBUTION - NONCOMMERCIAL 3.0
    UNITED STATES LICENSE
    For Complete Details please go to:
    http://creativecommons.org/licenses/by-nc/3.0/us/

PHP version 4.3.9 or greater is recommended
NOTE: This script requires PHP installed using GD image support.
http://us2.php.net/manual/en/ref.image.php

This version only works for jpg, png, and gif files.
It will not work for any other file type.

Some code is borrowed from Ken True - resize nexstorm-image.php script
http://saratoga-weather.org/scripts.php

################
# What does it do?:
# ##############

Multifunction Image Handler PHP Script
This script is a very easy to use multifunction image handler script
for your weather web site. The caching feature makes it the perfect
solution to gracefully "hot link" an image from another web site.

Some of the many features include:
    * Supports .jpg .gif and .png, download an image, cache the image,
    display the image
    * Supports remote images or local images on your web server
    * Convert the image type(optional)
    * Crop the image(optional)
    * Resize the image(optional)
    * Resize the image preserving aspect ratio(optional)
    * Jpeg compression(optional)
    * Annotate text on the image, add up to 3 text overlays(optional)
    * Multi line text support(optional)
    * Text alignment options(optional)
    * Text margin options(optional)
    * Text color options(optional)
    * Auto archive/rotate images with or without thumbs,
    this feature can be utilized for web cam image archiving(optional)
    * Outputs most errors as an image with error code.

################
# Why use it:
# ##############

Reduces bandwidth consumption that can annoy webmasters:
Even when you have permission to "hot link" to another site's image,
if your site generates too many requests for the image, they may get
annoyed and tell you to stop.
This script will considerably lighten the bandwidth consumption load.
Make thumbnail size images from larger ones: I use this script to make
a thumbnail image of of my web cam image for a link on my main page,
it even puts the words "Live Cam" on it.
See sample here:
http://www.642weather.com/weather/image-webcam-thumb.php
.. and it offers many other optional desirable features mentioned
in the "What does it do" section above.
Can also be used to output an image with web cam text overlay with up to 3
different overlay areas
Live Demo: http://www.642weather.com/weather/scripts-image-handler.php#IHdemo

################
# How to use it:
# ##############

1) Note: Please use common courtesy...
get permission to use the image you will download and display.
It is also nice to give credit on your page as to the source of the image
and provide a link to the source if possible.

2) Set your settings in the section below

3) Upload the contents of this file as a .php file in the same directory
your image will display.
Example: you want a radar image ...  name it image-radar.php

4) Call the file in the html where you want the image displayed
<img src="image-radar.php" alt="Radar Image" width="200" height="200" />

5) If you use this script ... please let me know ..
http://www.642weather.com/weather/contact_us.php
I would also appreciate a link to my weather site on your links page ...
Long Beach, WA Weather
http://www.642weather.com/weather/

Tip: If you are loading more than one image with this script,
be sure to uniquely name this script for each image.
and be sure to uniquely name each image file name in the setting below

Tip: This script can also be manually run from the web browser
for diagnostic purposes. No parameters are required for the script.

Tip: If you change a setting like image size,
the change may not show up instantly because the image may be cached.
You can force a download reload of the image with ?reload=1
like this: http://www.yoursite.com/image-radar.php?reload=1

Tip: If you get a PHP error about file permissions,
try changing the folder permissions to 755, or on some servers 777
http://www.stadtaus.com/en/tutorials/chmod-ftp-file-permissions.php

*/

//error_reporting(E_ALL); // Report all errors and warnings (very strict, use for testing only)
//ini_set('display_errors', 1); // turn error reporting on
#################
# begin settings
# ##############

#####
# where is the image you are downloading?
#####
$ImageURL = 'http://www.642weather.com/weather/webcamimage.jpg';
# note: both samples are correct as long as they are actual image files
# $ImageURL = 'http://www.somesite.com/radar_latest.php?site=kdmx&amp;prod=reflectivity1';
# $ImageURL = 'http://www.642weather.com/weather/webcamimage.jpg';
# Must start with http

# Note: This program will always save 2 image files to your web server
# $localimgName is a raw (temp image) file of the image downloaded
# $outputimgName is the (output image) for the web browser
# the following 2 settings will determine the file names.

#####
# The (temp image) - file name the image will be saved as on your server
#####
$localimgName = 'webcamimage-temp.jpg';
# note: use a unique name that is not a file on your server already
# or it will be OVERWRITTEN!
# note: only letters, numbers, dash, underscore, and dots allowed
# note: if the url being downloaded and the url of the file saved matches ..
# there will be an error so (use a different name for $localimgName)
# note: this script only supports .jpg .gif and .png
# note: this will convert png to jpg, png to gif, etc ..
# the extension you name it here is what it will be saved as
# note: If you are loading more than one image with this script,
# be sure to uniquely name this script for each image.
# Example: image-radar.php image-satellite.php
# ..and be sure to uniquely name each local image file
# Example:
# in image-radar.php,     name  $localimgName = 'image-radar-temp.jpg';
# in image-satellite.php, name  $localimgName = 'image-satellite-temp.jpg';

#####
# The (output image) - file name the image will be saved as on your server
#####
$outputimgName = 'webcamimage-cached.jpg';
# $localimgName and $outputimgName MUST HAVE SAME EXTENSION!
# note: use a unique name that is not a file on your server already
# or it will be OVERWRITTEN!
# note: If you are loading more than one image with this script,
# be sure to uniquely name this script for each image.
# Example: image-radar.php image-satellite.php
# ..and be sure to uniquely name each local image file
# Example:
# in image-radar.php,     name  $outputimgName = 'image-radar-cached.jpg';
# in image-satellite.php, name  $outputimgName = 'image-satellite-cached.jpg';

#####
# Local Directory - directory the images will be saved as on your server
#####
$localDirectory = './';
# use $localDirectory = './'; for same folder
# the folder must exist, you must make the folder yourself
# must end with a slash
# full path is recommended for cron scheduler use
# $localDirectory = '/var/www/html/weather/';

#####
# cache only option (to preserve animated GIFs when you do not need to resize, crop, or text overlay)
#####
$cache_only = 0; # just download and cache the file (ONLY!!), NO resize, NO crop, and NO text overlay
# Default set to 0 for no cache-only.
# note: setting this option $cache_only = 1;
# WILL BYPASS all other settings for resize, crop, and text overlay!!

#####
# resize options (uncomment only one of the settings below)
#####
// $resize_setting = 1; # use $new_width and $new_height
// $resize_setting = 2; # use $new_width
// $resize_setting = 3; # use $new_height
// $resize_setting = 4; # use $percent only to calculate $new_width $new_height
 $resize_setting = 5; # no resize
# 1) manual: use $new_width and $new_height settings below
# 2) use $new_width,  auto adjust height based on aspect ratio
# 3) use $new_height, auto adjust width  based on aspect ratio
# 4) use $percent only, image is resized by it's value in percent (i.e. 50 to downsize by 50 percent)
# 5) no resize

#####
# new image size for graphic display
#####
$new_width  = 400; # ignored with   $resize_setting 3 or 4
$new_height = 200; # ignored with   $resize_setting 2 or 4
$percent    =  50; # only used for  $resize_setting 4

#####
# jpeg compression percentage
#####
$jpegcompress = 95; # (range of 50 - 95 recommended)
# Example: 50 will make a smaller file but with less detail quality
#          95 will make a larger file but with very good detail quality
# used with $localimgName as a .jpg only, ignored for .gif or .png

#####
# Basic crop square from center - crops the image from calculated center in a square of $cropSize pixels
#####
$cropSize = 0;
# Default set to 0 for no basic crop.
# Example: $cropSize = 300; crops the image from calculated center to be a 300 pixel square.
# crop functions are performed on the original image BEFORE resize functions.
# resultant image can still be resized based on image resize options settings above.
# do not use basic and advance crop settings at the same time.

#####
# Advanced crop - crops an image using $cropStartX and $cropStartY as the upper-left hand corner.
#####
$cropStartX = 0; # crop from X pixels from upper-left hand corner.
$cropStartY = 0; # crop from Y pixels from upper-left hand corner.
$cropWidth  = 0; # crop area width  in pixels
$cropHeight = 0; # crop area height in pixels
# Default set to 0 for no advanced crop.
# crop functions are performed on the original image BEFORE resize functions.
# resultant image can still be resized based on image resize options settings above.
# do not use basic and advance crop settings at the same time.
# tip: a photo editor program will give you pixel X,Y locations to determine your crop settings

#####
# When to download a new image? (uncomment only one of the settings below)
#####
$download_setting = 1; # by last-modified
//$download_setting = 2; # by time interval
//$download_setting = 3; # always
# 1) only when the image last-modified timestamp changes at the source,
# 2) at a preset time interval like every 5 minutes,
# 3) always: (download and resize every hit)(less recommended, but good for testing)

#####
# Download new image every nnn seconds: like 600 for 5 minutes
#####
# note: only used with $download_setting = 2;
$refetchSeconds = 600;

#####
# Annotate text on image (optional, useful for text overlay on your image)
#####
$text1 = ''; # leave empty for no text1
$text2 = ''; # leave empty for no text2
$text3 = ''; # leave empty for no text3
# Note: $text1 = ''; no text will apear on the image
# See sample here: http://www.642weather.com/weather/image-webcam-thumb.php
# Example: $text1 = 'Live Cam';
# Multiline text also supported ...
# $text1 = 'Live
# Cam';
# See sample here: http://www.642weather.com/weather/scripts-image-handler.php#IHdemo

# Text alignment
$textalign1 = 'upperleft';
$textalign2 = 'lowerleft';
$textalign3 = 'centerbottom';
# your textalign options are ...
# upperright upperleft lowerleft lowerright center centertop centerbottom
$xmargin1 = 5; # side margin in pixels
$xmargin2 = 5; # side margin in pixels
$xmargin3 = 5; # side margin in pixels
$ymargin1 = 5; # top or bottom margin in pixels
$ymargin2 = 5; # top or bottom margin in pixels
$ymargin3 = 5; # top or bottom margin in pixels

# Font style
$fontstyle1 = 5; # There are 5 built in GD fonts: 1 2 3 4 5 ONLY!
$fontstyle2 = 5; # There are 5 built in GD fonts: 1 2 3 4 5 ONLY!
$fontstyle3 = 5; # There are 5 built in GD fonts: 1 2 3 4 5 ONLY!
# $fontstyle GD fonts can be overridden with true type fonts, see below

# Font color in Hex
$fontcolor1 = 'FFFFFF'; # FFFFFF white
$fontcolor2 = 'FFFFFF'; # FFFFFF white
$fontcolor3 = 'FFFFFF'; # FFFFFF white
# Font drop shadow color in Hex
$fontshadowcolor1 = '808080'; # 808080 grey
$fontshadowcolor2 = '808080'; # 808080 grey
$fontshadowcolor3 = '808080'; # 808080 grey
# free online hex color picker http://www.colorschemer.com/online.html

# Override built in (Font style) fonts with a True Type Font
$ttfont1 = ''; # (READ NOTE BELOW!)
$ttfont2 = ''; # (READ NOTE BELOW!)
$ttfont3 = ''; # (READ NOTE BELOW!)
$fontsize1 = 13; # size for True Type Font1 only (8-18 recommended)
$fontsize2 = 13; # size for True Type Font2 only (8-18 recommended)
$fontsize3 = 13; # size for True Type Font3 only (8-18 recommended)
# Example: $ttfont1 = 'arial.ttf'
# Note: for $ttfont1 = ''; $fontstyle1 above is used
# DO NOT USE UNLESS YOU HAVE arial.ttf file in the same directory as this script!
# Any .ttf font files are supported,
# get free fonts: http://www.google.com/search?hl=en&amp;q=free+ttf+fonts
# full path is recommended for cron scheduler use
# $ttfont1 = '/var/www/html/mosaic/htdocs/weather/arial.ttf';

$browser_output_only = 0;
# $browser_output_only = 0; # normal usage: saves the resultant image file
# $browser_output_only = 1; # demo usage: outputs resultant image to a web browser ONLY

# suppress browser image output for cron job or scheduled task usage
$no_output = 0;
# $no_output = 0; # normal usage: saves a image file and displays it to a web browser
# $no_output = 1; # save image file only, no image to browser, output url link to browser
# see here for a tutorial ..
# http://www.642weather.com/weather/scripts-weather-cam-text.php
# Simple guide to crontab usage: http://en.wikipedia.org/wiki/Cron
# Scheduled HTTP Request - Windows Task Scheduler:
# http://www.642weather.com/weather/wxblog/php-scripts/scheduled-http-request-windows-task-scheduler/

# use curl to get last_modified time from a remote URL file
# set to 0 if your PHP does not support CURL
$use_curl = 1;

# Set permissions of images 0644 (www readable)
$chmod = 0;
# disabled by default, most servers do not need it.
# enable it only if your images do not load from a web page even though they are on the server.
# $chmod = 0; # Disabled
# $chmod = 1; # Enabled

#####
# Auto archive images feature (great for web cam images)
#####
$archive = 0;
# $archive = 0; # Disabled
# $archive = 1; # Enabled
# Live example: http://www.642weather.com/weather/cam-history.php
# Thanks Jim McMurry at http://www.jcweather.us/ for the archive feature code idea/suggestion

# How many archived images will be stored
$archivecount = 12;
# example setting: $archivecount = 12;
# only this many will be saved at a time, new ones are placed at webcamimage0.jpg
# newest image will be webcamimage0.jpg ... oldest image will be webcamimage12.jpg

# Where will the archived images be saved
$archivedir = './webcam/';
# use $archivedir = './'; for same folder, or something like this: $archivedir = './webcam/';
# best to put them in their own folder though
# the folder must exist, you must make the folder yourself
# must end with a slash
# full path is recommended for cron scheduler use
# $archivedir = '/var/www/html/mosaic/htdocs/weather/webcam/';

# prefix of the archived file name
$archivefilepre = 'webcamimage'; # no extension!! the 0.jpg part will be autogenerated
# example setting: $archivefilepre = 'webcamimage';
# newest image will be webcamimage0.jpg

# autogenerate thumb images of the archived?
$archivewiththumbs = 0;
# $archivewiththumbs = 0; # Disabled
# $archivewiththumbs = 1; # Enabled
# newest image will be webcamimage0.jpg and newest thumb will be webcamimage0-thm.jpg
$thumb_new_width  = 100; # thumb image width size (height will auto size)

#####
# memory_limit is a safety incase downloaded file is 1 gig or something
#####
# DO NOT CHANGE THIS unless you really know what you are doing
# if you get "out of memory error" on a normal size image,
# then you may want to increase the value slightly
# not all php installs have this setting enabled so it is commented out by default
# ini_set ("memory_limit", "10M");

#####
# If you find any bugs,
# or can think of other possible settings/features for future releases:
# Contact Mike - http://www.642weather.com/weather/contact_us.php
#####

/*
# sometimes an error code can be printed in the image
# possible errors that could show up in the image are:
Error 000: Forbidden characters in $localimgName only letters, numbers, dash, underscore, and dots allowed
Error 001: Forbidden characters in $outputimgName only letters, numbers, dash, underscore, and dots allowed
Error 002: $localimgName file type not gif, jpg, or png. This script only supports .jpg .gif and .png
Error 003: Download error: cannot write to file, check server permission settings
Error 004: Download error: reading or opening file, check availability of $ImageURL
Error 005: Error loading image
Error 006: Missing downloaded temp file
Error 007: Convert_download: file not gif, jpg, or png. This script only supports .jpg .gif and .png
Error 008: Missing cache file
Error 009: Missing downloaded file
Error 010: Copy cache image failed
Error 011: Convert_download: touch image last modified time failed
Error 012: Chmod 0644 image failed
Error 015: Wrong settings: $localimgName and $outputimgName must have same extension IE: .jpg .gif or .png
Error 016: $outputimgName file type not gif, jpg, or png. This script only supports .jpg .gif and .png
Error 017: $localimgName and $outputimgName cannot be named the same
Error 018: fetching timestamp failed for URL (remote_image) 404 not found?
Error 019: could not connect to remote image
Error 020: $ImageURL must start with http
*/


#################
# end settings
#################

#####                                                                      #####
# Do not alter any code below this point in the script or it may not run properly.
#####                                                                      #####

if (isset($_REQUEST['sce']) &amp;&amp; strtolower($_REQUEST['sce']) == 'view' ) {
   //--self downloader --
   $filenameReal = __FILE__;
   $download_size = filesize($filenameReal);
   header('Pragma: public');
   header('Cache-Control: private');
   header('Cache-Control: no-cache, must-revalidate');
   header("Content-type: text/plain");
   header("Accept-Ranges: bytes");
   header("Content-Length: $download_size");
   header('Connection: close');
   readfile($filenameReal);
   exit;
}

# make sure the GD library is installed
if ( !extension_loaded('gd') || !function_exists('gd_info') ) {
   echo 'You do not have the GD Library installed.
   This script requires the GD library to function properly.
   visit http://us2.php.net/manual/en/ref.image.php for more information'
;
   exit;
}

// fall back if CURL is not installed.
if($use_curl &amp;&amp; !function_exists('curl_init') ) {
    $use_curl = 0;
}

if (!preg_match('/^http/i', $ImageURL)) errorIMG('020');
# sanitize the string no html tags, spaces,
# allow only letters, numbers, dash, underscore, and dots
$localimgName = strip_tags($localimgName, '');
$localimgName = preg_replace('/ /', '', $localimgName);
if (preg_match("/[^\w\.-]+/", $localimgName)) errorIMG('000');
$outputimgName = strip_tags($outputimgName, '');
$outputimgName = preg_replace('/ /', '', $outputimgName);
if (preg_match("/[^\w\.-]+/", $outputimgName)) errorIMG('001');
if (!preg_match('/\.(jpg|gif|png)$/i', $localimgName)) errorIMG('002');
if (!preg_match('/\.(jpg|gif|png)$/i', $outputimgName)) errorIMG('016');
# $localimgName and $outputimgName cannot be named the same
if ($localimgName == $outputimgName) errorIMG('017');
# $localimgName and $outputimgName must have same extension
if (substr($localimgName,-3) != substr($outputimgName,-3)) errorIMG('015');

################# get the image, cache it and display it ############

$islocal = 0;
# is $ImageURL a local file in this same folder?
# if yes, no need to download it, still ok to cache and resize though
if (empty($_SERVER['SCRIPT_URI'])) {
   $_SERVER['SCRIPT_URI'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
$scripturlparts = explode('/', $_SERVER['SCRIPT_URI']);
$scriptfilename = $scripturlparts[count($scripturlparts)-1];
$scripturl = preg_replace("/$scriptfilename$/i", '', $_SERVER['SCRIPT_URI']);

if (preg_match('/\.(jpg|gif|png)$/i', $ImageURL)) {
  $ImageURLparts = explode('/', $ImageURL);
  $Imagefilename = $ImageURLparts[count($ImageURLparts)-1];
  $imageurl = preg_replace("/$Imagefilename$/i", '', $ImageURL);
  if(strtolower($imageurl) == strtolower($scripturl)) {
    $islocal = 1;
    $Imagefilename = $localDirectory . $Imagefilename;
  }
}

# filetype will be forced to the file type
# selected for $localimgName display image
$FileType = substr($localimgName,-3);
$Graphic = $localDirectory . $localimgName;
$Cache =   $localDirectory . $outputimgName;

$havefile = 0;
if (file_exists($Cache)){
# see if an image is cached and how old it is
       $havefile =1;
        if (!file_exists($Graphic)) errorIMG('009');
        if ($islocal) {
              // wait 2 seconds incase it is being re-uploaded
              if (!file_exists($Imagefilename) || !is_readable($Imagefilename)) sleep(3);
              $GraphicTime = filectime($Imagefilename);
        }else{
              $GraphicTime = filectime($Graphic);
        }
        $CacheTime = filectime($Cache);
        if(!$islocal){
          if($use_curl) {
                  $URLdate = curl_last_mod($ImageURL);
          } else {
                  $Headers = getHTTPheaders($ImageURL,1);
                  $URLdate = strtotime($Headers['last-modified']);
          }
        }
        if ((!$islocal and $download_setting ==1 and $URLdate > $GraphicTime)||
        ($islocal and $download_setting ==1 and $GraphicTime > $CacheTime)) {
           # download new image because
          # last-modified timestamp changes at the source
          if($islocal) copy_file($Imagefilename, $Graphic);
           if(!$islocal) {
             if ($use_curl) {
                     curl_download_file($ImageURL, $Graphic);
             } else {
                     download_file($ImageURL, $Graphic);
             }
           }
           if ($cache_only) {
                   cache_download($Graphic);
           } else {
                   convert_download($Graphic);
           }
        }
        if ($download_setting ==2 and file_exists($Cache) and filemtime($Cache) + $refetchSeconds < time()) {
           # download new image at the preset time interval
          if($islocal) copy_file($Imagefilename, $Graphic);
           if(!$islocal) {
             if ($use_curl) {
                     curl_download_file($ImageURL, $Graphic);
             } else {
                     download_file($ImageURL, $Graphic);
             }
           }
           if ($cache_only) {
                   cache_download($Graphic);
           } else {
                   convert_download($Graphic);
           }
        }
        if ($download_setting ==3 || $_GET['reload'] == 1) {
           # download new image every hit
          if($islocal)  copy_file($Imagefilename, $Graphic);
           if(!$islocal) {
             if ($use_curl) {
                     curl_download_file($ImageURL, $Graphic);
             } else {
                     download_file($ImageURL, $Graphic);
             }
           }
           if ($cache_only) {
                   cache_download($Graphic);
           } else {
                   convert_download($Graphic);
           }
        }
        $GraphicTime = filectime($Graphic);
} else {
       # download the first time
      if($islocal)  copy_file($Imagefilename, $Graphic);
       if(!$islocal) {
             if ($use_curl) {
                     curl_download_file($ImageURL, $Graphic);
             } else {
                     download_file($ImageURL, $Graphic);
             }
           }
       if ($cache_only) {
               cache_download($Graphic);
       } else {
               convert_download($Graphic);
       }
}

if($no_output == 1) {
      echo "You have setting mode: \$no_output =1;<br>
      suppress browser image output for cron job or scheduled task usage<br>
      Here is a URL to your image:<br>
      <a href=\"$scripturl$outputimgName\">$scripturl$outputimgName</a>"
;
}else{
      if (file_exists($Cache)) {
        # now send image to browser
       if($_GET['reload'] == 1) {
              header('Last-modified: ' . gmdate("D, d M Y H:i:s"). ' GMT');
        }elseif(!$islocal) {
              header('Last-modified: ' . $Headers['last-modified']);
        }else{
              header('Last-modified: ' . gmdate("D, d M Y H:i:s", filectime($Graphic)). ' GMT');
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        header('Content-Length: '.filesize($Cache));
        if ($FileType == 'jpg') header("Content-type: image/jpeg");
        if ($FileType == 'gif') header("Content-type: image/gif");
        if ($FileType == 'png') header("Content-type: image/png");
         readfile($Cache);
     } else {
             errorIMG('008');
     }
}
exit;

############# Begin Functions #################

function cache_download($Graphic) {
# cache only option (this will preserve animated GIFS)
# just download and cache the file (ONLY!!)
# will bypass all other settings for resize, crop, and text overlay!!
# NO resize, NO crop, and NO text overlay

   global $chmod, $archive, $Cache, $islocal;

   # is anyhing there?
  if (is_file($Graphic)) {
      list($width, $height, $type) = getimagesize($Graphic);
      $new_ext ='';
      switch($type) {
        case "1": $new_ext = 'gif';
        break;
        case "2": $new_ext = 'jpg';
        break;
        case "3": $new_ext = 'png';
        break;
      }
      !preg_match('/(jpg|gif|png)$/i', $new_ext) and errorIMG('007');
      copy($Graphic, $Cache);
      # update file last modified if it is a local image and we are forcing reload
     if($islocal and $_GET['reload'] == 1) touch($Graphic) or errorIMG('011');
      if ($chmod) chmod($Cache, 0644) or errorIMG('012');
      # archive?
     if($archive) {
        //Begin archive Sequencing
        archive_file($Cache);
      }
   } else {
           errorIMG('006');
   }
} // end function cache_download

function makethumb($file,$thumbfile) {
    global $thumb_new_width, $chmod, $jpegcompress;
   # is anyhing there?
  if (is_file($file)) {
      list($width, $height, $type) = getimagesize($file);
      $new_ext ='';
      switch($type) {
        case "1": $new_ext = 'gif';
        break;
        case "2": $new_ext = 'jpg';
        break;
        case "3": $new_ext = 'png';
        break;
      }
      !preg_match('/(jpg|gif|png)$/i', $new_ext) and errorIMG('007');
      # resize to $thumb_new_width set width but keep proportion
     $thumb_new_height = round($height * $thumb_new_width / $width);
      $imageb = loadIMG($file);
      $imaget = imagecreatetruecolor($thumb_new_width, $thumb_new_height);
      imagecopyresampled($imaget, $imageb, 0, 0, 0, 0, $thumb_new_width, $thumb_new_height, $width, $height);
      # save image
     if ($new_ext == 'jpg') imagejpeg($imaget, $thumbfile, $jpegcompress);
      if ($new_ext == 'gif') imagegif($imaget, $thumbfile);
      if ($new_ext == 'png') imagepng($imaget, $thumbfile);
      imagedestroy($imageb);
      imagedestroy($imaget);
      if ($chmod) chmod($thumbfile, 0644);
   }# end if is file

} // end function make_thumb

function new_width_height($width,$height){
     global $resize_setting, $new_width, $new_height, $percent;
      # no resize
     if ($resize_setting ==5 ) {
         $resize_setting =4; $percent = 100;
      }
      # resize to $new_width  set width  but keep proportion
     $resize_setting ==2 and $new_height = round($height * $new_width / $width);
      # resize to $new_height  set height  but keep proportion
     $resize_setting ==3 and $new_width = round($width * $new_height / $height);
      # use $percent to calculate $new_width $new_height
     if ($resize_setting ==4 ) {
         $percent = $percent * 0.01;
         $new_width = $width * $percent;
         $new_height = $height * $percent;
      }
      return array ($new_width,$new_height);
} // end function new_width_height

function convert_download($Graphic) {
   global $new_width, $new_height, $Cache, $FileType, $percent, $browser_output_only;
   global $resize_setting, $jpegcompress, $chmod, $text1, $text2, $text3, $archive;
   global $cropSize, $cropStartX, $cropStartY, $cropWidth, $cropHeight, $islocal;

   # is anyhing there?
  if (is_file($Graphic)) {
      list($width, $height, $type) = getimagesize($Graphic);
      $new_ext ='';
      switch($type) {
        case "1": $new_ext = 'gif';
        break;
        case "2": $new_ext = 'jpg';
        break;
        case "3": $new_ext = 'png';
        break;
      }
      !preg_match('/(jpg|gif|png)$/i', $new_ext) and errorIMG('007');

      # convert and resize
        $image = loadIMG($Graphic);
         # Basic crop from center - crops the image from calculated center in a square of $cropSize pixels
        $cropped=0;
         if($cropSize > 0) {
           $cropX =0;
           $cropY =0;
           $cropSize > $width  and $cropSize = $width;
           $cropSize > $height and $cropSize = $height;
           $cropX = intval(($width - $cropSize) / 2);
           $cropY = intval(($height - $cropSize) / 2);
           $image_c = imagecreatetruecolor($cropSize, $cropSize);
           list ($new_width, $new_height) = new_width_height($cropSize, $cropSize);
           $image_p = imagecreatetruecolor($new_width, $new_height);
           imagecopyresampled($image_c, $image, 0, 0, $cropX, $cropY, $cropSize, $cropSize, $cropSize, $cropSize);
           imagecopyresampled($image_p, $image_c, 0, 0, 0, 0, $new_width, $new_height, $cropSize, $cropSize);
           $cropped=1;
         }
         # Advanced crop - crops an image using $cropStartX and $cropStartY as the upper-left hand corner.
        if(!$cropped and $cropWidth > 0 and $cropHeight > 0) {
           list ($new_width, $new_height) = new_width_height($cropWidth,$cropHeight);
           $cropWidth >  $width  and $cropWidth = $width;
           $cropHeight > $height and $cropHeight = $height;
           if(($cropStartX + $cropWidth) > $width)   $cropStartX = ($width - $cropWidth);
           if(($cropStartY + $cropHeight) > $height) $cropStartY = ($height - $cropHeight);
           $cropStartX < 0 and $cropStartX = 0;
           $cropStartY < 0 and $cropStartY = 0;
           $image_c = imagecreatetruecolor($cropWidth, $cropHeight);
           $image_p = imagecreatetruecolor($new_width, $new_height);
           imagecopyresampled($image_c, $image, 0, 0, $cropStartX, $cropStartY, $cropWidth, $cropHeight, $cropWidth, $cropHeight);
           imagecopyresampled($image_p, $image_c, 0, 0, 0, 0, $new_width, $new_height, $cropWidth, $cropHeight);
           $cropped=1;
         }
         if (!$cropped) {
              list ($new_width, $new_height) = new_width_height($width,$height);
              $image_p = imagecreatetruecolor($new_width, $new_height);
              imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
         }
         $text1 != '' and textoverlay(1,$image_p, $new_width, $new_height);
         $text2 != '' and textoverlay(2,$image_p, $new_width, $new_height);
         $text3 != '' and textoverlay(3,$image_p, $new_width, $new_height);
         if($browser_output_only) {
                 # send image to browser only (DEMO MODE)
                header('Last-modified: ' . gmdate("D, d M Y H:i:s"). ' GMT');
                 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                 header("Cache-Control: no-store, no-cache, must-revalidate");
                 header("Cache-Control: post-check=0, pre-check=0", false);
                 header("Pragma: no-cache");
                 if ($FileType == 'jpg') header("Content-type: image/jpeg");
                 if ($FileType == 'gif') header("Content-type: image/gif");
                 if ($FileType == 'png') header("Content-type: image/png");
                 if ($FileType == 'jpg') imagejpeg($image_p, '', $jpegcompress);
                 if ($FileType == 'gif') imagegif($image_p);
                 if ($FileType == 'png') imagepng($image_p);
                 imagedestroy($image);
                 imagedestroy($image_p);
                 exit;
         } else {
                 # save image (NORMAL MODE)
                if ($FileType == 'jpg') imagejpeg($image_p, $Cache, $jpegcompress);
                 if ($FileType == 'gif') imagegif($image_p, $Cache);
                 if ($FileType == 'png') imagepng($image_p, $Cache);

         }
         $cropped and imagedestroy($image_c);
         imagedestroy($image);
         imagedestroy($image_p);
         # update file last modified if it is a local image and we are forcing reload
        if($islocal and $_GET['reload'] == 1) touch($Graphic) or errorIMG('011');
   } else {
           errorIMG('006');
   }
   if ($chmod) chmod($Cache, 0644) or errorIMG('012');
   # archive?
  if($archive) {
     //Begin archive Sequencing
     archive_file($Cache);
   }
} // end of convert_download function

function archive_file($Cache) {

   global $FileType, $chmod, $archive, $archivecount, $archivedir, $archivefilepre, $archivewiththumbs;

  //Begin archive Sequencing
  # delete oldest file
 $targetfile = $archivedir . $archivefilepre . $archivecount . '.' .$FileType;
  $targetfilethm = $archivedir . $archivefilepre . $archivecount . '-thm.' .$FileType;
  if (file_exists($targetfile)) unlink($targetfile);
  if ($archivewiththumbs and file_exists($targetfilethm)) unlink($targetfilethm);
  # archive/rotate the rest
 for($i = $archivecount-1; $i >= 0; $i--){ //cycle through files renaming them
     $targetfile = $archivedir . $archivefilepre . $i . '.' .$FileType;
     $targetfilethm = $archivedir . $archivefilepre . $i . '-thm.' .$FileType;
     $t = $i + 1;
     $nextfile = $archivedir . $archivefilepre . $t . '.' .$FileType;
     $nextfilethm = $archivedir . $archivefilepre . $t . '-thm.' .$FileType;
     if (file_exists($targetfile)) rename($targetfile, $nextfile);
     if ($archivewiththumbs and file_exists($targetfilethm)) rename($targetfilethm, $nextfilethm);
  }
  # add newest file
 $targetfile = $archivedir . $archivefilepre . '0.' . $FileType;
  copy($Cache, $targetfile);
  if ($chmod) chmod($targetfile, 0644) or errorIMG('012');
  if($archivewiththumbs) {
    makethumb("$archivedir$archivefilepre" . '0.' . "$FileType","$archivedir$archivefilepre" . '0-thm.' . "$FileType");
  }
} // end of archive_file function

function textoverlay($textoption,$image_p, $new_width, $new_height) {
    global $text1, $ttfont1, $fontsize1, $fontcolor1, $fontshadowcolor1, $fontstyle1, $textalign1, $xmargin1, $ymargin1;
    global $text2, $ttfont2, $fontsize2, $fontcolor2, $fontshadowcolor2, $fontstyle2, $textalign2, $xmargin2, $ymargin2;
    global $text3, $ttfont3, $fontsize3, $fontcolor3, $fontshadowcolor3, $fontstyle3, $textalign3, $xmargin3, $ymargin3;
    if ($textoption == 1) {
      $text = $text1; $ttfont = $ttfont1; $fontsize = $fontsize1; $fontstyle = $fontstyle1;
      $fontcolor = $fontcolor1; $fontshadowcolor = $fontshadowcolor1;
      $textalign = $textalign1; $xmargin = $xmargin1; $ymargin = $ymargin1;
    }
    if ($textoption == 2) {
      $text = $text2; $ttfont = $ttfont2; $fontsize = $fontsize2; $fontstyle = $fontstyle2;
      $fontcolor = $fontcolor2; $fontshadowcolor = $fontshadowcolor2;
      $textalign = $textalign2; $xmargin = $xmargin2; $ymargin = $ymargin2;
    }
    if ($textoption == 3) {
      $text = $text3; $ttfont = $ttfont3; $fontsize = $fontsize3; $fontstyle = $fontstyle3;
      $fontcolor = $fontcolor3; $fontshadowcolor = $fontshadowcolor3;
      $textalign = $textalign3; $xmargin = $xmargin3; $ymargin = $ymargin3;
    }
    if (!preg_match('#[a-z0-9]{6}#i', $fontcolor)) $fontcolor = 'FFFFFF';  # default white
   if (!preg_match('#[a-z0-9]{6}#i', $fontshadowcolor)) $fontshadowcolor = '808080'; # default grey
   $fcint = hexdec("#$fontcolor");
    $fsint = hexdec("#$fontshadowcolor");
    $fcarr = array("red" => 0xFF &amp; ($fcint >> 0x10),"green" => 0xFF &amp; ($fcint >> 0x8),"blue" => 0xFF &amp; $fcint);
    $fsarr = array("red" => 0xFF &amp; ($fsint >> 0x10),"green" => 0xFF &amp; ($fsint >> 0x8),"blue" => 0xFF &amp; $fsint);
    $fcolor  = imagecolorallocate($image_p, $fcarr["red"], $fcarr["green"], $fcarr["blue"]);
    $fscolor = imagecolorallocate($image_p, $fsarr["red"], $fsarr["green"], $fsarr["blue"]);
    if ($ttfont != '') {
       # using ttf fonts
      $alpha   = range("a", "z");
       $alpha_u = range("A", "Z");
       $alpha = $alpha.$alpha_u.range(0, 9);
       $_b = imageTTFBbox($fontsize,0,$ttfont,$alpha);
       $fontheight = abs($_b[7]-$_b[1]);
    } else {
      $font = $fontstyle;
      # using built in fonts, find alignment
     if($font < 0 || $font > 5){ $font = 1; }
          $fontwidth = ImageFontWidth($font);
          $fontheight = ImageFontHeight($font);
      }
      $text = preg_replace("/\r/",'',$text);
      # wordwrap line if too many characters on one line
     if ($ttfont != '') {
         # array lines
        $lines = explode("\n", $text);
         $lines = ttf_wordwrap($lines,$ttfont,$fontsize,floor($new_width - ($xmargin * 2)));
      } else {
        $maxcharsperline = floor(($new_width - ($xmargin * 2)) / $fontwidth);
        $text = wordwrap($text, $maxcharsperline, "\n", 1);
        # array lines
       $lines = explode("\n", $text);
      }
      # determine alignment
     $align = 'ul'; # default upper left
     if ($textalign == 'lowerleft')    $align = 'll';
      if ($textalign == 'upperleft')    $align = 'ul';
      if ($textalign == 'lowerright')   $align = 'lr';
      if ($textalign == 'upperright')   $align = 'ur';
      if ($textalign == 'center')       $align = 'c';
      if ($textalign == 'centertop')    $align = 'ct';
      if ($textalign == 'centerbottom') $align = 'cb';
      # find start position for each text position type
     if ($align == 'ul') { $x = $xmargin; $y = $ymargin;}
      if ($align == 'll') { $x = $xmargin;
         $y = $new_height - ($fontheight + $ymargin);
         $lines = array_reverse($lines);
      }
      if ($align == 'ur') $y = $ymargin;
      if ($align == 'lr') { $x = $xmargin;
         $y = $new_height - ($fontheight + $ymargin);
         $lines = array_reverse($lines);
      }
      if ($align == 'ct') $y = $ymargin;
      if ($align == 'cb') { $x = $xmargin;
         $y = $new_height - ($fontheight + $ymargin);
         $lines = array_reverse($lines);
      }
      if ($align == 'c') $y = ($new_height/2) - ((count($lines) * $fontheight)/2);
      if ($ttfont != '') $y +=$fontsize; # fudge adjustment for truetype margin
        while (list($numl, $line) = each($lines)) {
             # adjust position for each text position type
            if ($ttfont != '') {
                $_b = imageTTFBbox($fontsize,0,$ttfont,$line);
                $stringwidth = abs($_b[2]-$_b[0]);
             }else{
                $stringwidth = strlen($line) * $fontwidth;
             }
             if ($align == 'ur'||$align == 'lr') $x = ($new_width - ($stringwidth) - $xmargin);
             if ($align == 'ct'||$align == 'cb'||$align == 'c') $x = $new_width/2 - $stringwidth/2;
             if ($ttfont != '') {
                # write truetype font text with slight SE shadow to standout
               imagettftext($image_p, $fontsize, 0, $x-1, $y, $fscolor, $ttfont, $line);
                imagettftext($image_p, $fontsize, 0, $x, $y-1, $fcolor, $ttfont, $line);
             }else{
                # write text with slight SE shadow to standout
               imagestring($image_p,$font,$x-1,$y,$line,$fscolor);
                imagestring($image_p,$font,$x,$y-1,$line,$fcolor);
             }
             # adjust position for each text position type
            if ($align == 'ul'||$align == 'ur'||$align == 'ct'||$align == 'c') $y += $fontheight;
             if ($align == 'll'||$align == 'lr'||$align == 'cb') $y -= $fontheight;
         } # end while
} // end textoverlay function

function errorIMG($error) {
   global $no_output;
   # shows error messages in an image output
  # no image is actually written to server, just to web browser
  global $new_width, $new_height, $no_output;
 if($no_output) {
   echo "Error: $error";
 }else{
   $im  = imagecreate ($new_width, $new_height);
   $bgc = imagecolorallocate ($im, 255, 255, 255);
   $tc  = imagecolorallocate ($im, 0, 0, 0);
   imagefilledrectangle ($im, 0, 0, $new_width, $new_height, $bgc);
   imagestring ($im, 5, 5, 5, "Error: $error", $tc);
   header('Content-type: image/gif');
   imagegif($im);
   imagedestroy($im);
 }
   exit;
} // end of errorIMG function


function loadIMG($imgname) {
  # have to get the right filetype based on what the image actually is,
 # not what it is going to be saved as later
 if (is_file($imgname)) {
      list($width, $height, $type) = getimagesize($imgname);
      $new_ext ='';
      switch($type) {
        case "1": $new_ext = 'gif';
        break;
        case "2": $new_ext = 'jpg';
        break;
        case "3": $new_ext = 'png';
        break;
      }
      if (!preg_match('/(jpg|gif|png)$/i', $new_ext)) {
        errorIMG('007');
      }
  }
  if ($new_ext == 'jpg')$im = @imagecreatefromjpeg($imgname);
  if ($new_ext == 'gif')$im = @imagecreatefromgif($imgname);
  if ($new_ext == 'png')$im = @imagecreatefrompng($imgname);
  if (!$im) {
       errorIMG('005');
  }
  return $im;
} // end of loadIMG function

function curl_last_mod($remote_file) {
    // return unix timestamp (last_modified) from a remote URL file
    $last_modified = $ch = $resultString = $headers = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_file);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5 sec timeout
    curl_setopt($ch, CURLOPT_HEADER, 1);  // make sure we get the header
    curl_setopt($ch, CURLOPT_NOBODY, 1);  // make it a http HEAD request
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // write the response to a variable
    curl_setopt($ch, CURLOPT_FILETIME, 1 );

    $i = 1;
    while ($i++ <= 2) {
       if(curl_exec($ch) === false){
               errorIMG('019'); // could not connect
               //   echo 'Curl error: ' . curl_error($ch);
               //   exit;
       }
       $headers = curl_getinfo($ch);
       if ($headers['http_code'] != 200 &amp;&amp; $headers['http_code'] != 203) {
          sleep(3);  // Let's wait 3 seconds to see if its a temporary network issue.
       } else if ($headers['http_code'] == 200 || $headers['http_code'] == 203) {
          // we got a good response, drop out of loop.
          break;
       }
    }
    $last_modified = $headers['filetime'];
    if ($headers['http_code'] != 200 &amp;&amp; $headers['http_code'] != 203) errorIMG('018'); // remote file not found
    curl_close ($ch);

    return $last_modified;
} // end of curl_last_mod function

function getHTTPheaders($url,$format=0) {
  $url_info=parse_url($url);
  $port = isset($url_info['port']) ? $url_info['port'] : 80;
  $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 15);
  if($fp) {
    $head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
    $head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
    fputs($fp, $head);
    while(!feof($fp)) {
      if($header=trim(fgets($fp, 1024))) {
        if($format == 1) {
          $h2 = explode(': ',$header);
// the first element is the http header type, such as HTTP/1.1 200 OK,
// it doesn't have a separate name, so we have to check for it.
          if($h2[0] == $header) {
            $headers['status'] = $header;
              if ( !preg_match('|HTTP/1.* 200 OK|i',$header) &amp;&amp; !preg_match('|HTTP/1.* 203|i',$header)) {
                errorIMG('018'); // 404 image?
                exit;
              }
          } else {
            $headers[strtolower($h2[0])] = trim($h2[1]);
          }
        } else {
          $headers[] = $header;
        }
      }
    }
          fclose($fp);
          return $headers;
  } else {
          errorIMG('019'); // could not connect
          exit;
  }
} // end of getHTTPheaders function

function copy_file($file_source, $file_target) {
  global $chmod;
  // wait incase it is being re-uploaded
  if (!file_exists($Imagefilename) || !is_readable($Imagefilename)) sleep(3);
  copy($file_source, $file_target) or errorIMG('011');
  if ($chmod) chmod($file_target, 0644) or errorIMG('012');
  // No error
  return false;
} // end of copy_file function

function download_file($file_source, $file_target) {
  global $chmod;
  $rh = fopen($file_source, 'rb') or errorIMG('004');
  $wh = fopen($file_target, 'wb') or errorIMG('003');
  while (!feof($rh)) {
    if (fwrite($wh, fread($rh, 1024)) === FALSE) {
          errorIMG('003');
          return true;
    }
  }
  fclose($rh);
  fclose($wh);
  if ($chmod) chmod($file_target, 0644) or errorIMG('012');
  // No error
  return false;
} // end of download_file function

function curl_download_file($file_source, $file_target) {
  global $chmod;

  $wh = fopen($file_target, 'wb') or errorIMG('003');
  $ch = curl_init($file_source);  // the file we are downloading
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_FILE, $wh);
  //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($wh);

  if ($chmod) chmod($file_target, 0644) or errorIMG('012');

  return false;
} // end of curl_download_file function

function ttf_wordwrap($srcLines,$font,$textSize,$width) {
    $dstLines = Array(); // The destination lines array.
    foreach ($srcLines as $currentL) {
        $line = '';
        $words = explode(" ", $currentL); //Split line into words.
        foreach ($words as $word) {
            $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$word);
            $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line, if the word is to be included
            if ($lineWidth > $width &amp;&amp; !empty($line) ) { // check if it is too big if the word was added, if so, then move on.
                $dstLines[] = trim($line); //Add the line like it was without spaces.
                $line = '';
            }
            $line .= $word.' ';
        }
        $dstLines[] =  trim($line); //Add the line when the line ends.
    }
    return $dstLines;
} // end of ttf_wordwrap function
?></pre>
&amp;nbsp;

Scripts for Zoom – Highslide Image Handling

Zoom-Highslide is a zoom and highslide plugin for wordpress, it works mainly as highslide to make photo show beautiful.

 

<?php
/*
Plugin Name: Zoom-Highslide
Plugin URI: http://ziming.org/dev/zoom-highslide
Description: This plugin integrate image zoom and highslide effect to make photo show beautiful.
Version: 1.2.1
Highslide Version: 4.2
Author: Suny Tse
Author URI: http://ziming.org
*/


/*  Copyright 2010  Suny Tse  (email : message@ziming.org)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/


define("IMAGE_FILETYPE", "(bmp|gif|jpeg|jpg|png)", true);

init_check();
function init_check(){
 $options = get_option('zoom_highslide');
 if(!$options['widthRestriction']){
 $options['widthRestriction'] = '640';
 }
 if(!$options['heightRestriction']){
 $options['heightRestriction'] = '1000';
 }
 if(!$options['show_interval']){
 $options['show_interval'] = 5000;
 }
 if(!$options['controler_position']){
 $options['controler_position'] = 'top center';
 }
 if(!$options['background_opacity']){
 $options['background_opacity'] = 0.8;
 }
 if(!update_option('zoom_highslide', $options)){
 add_option('zoom_highslide', $options);
 }
}

/*******************************  Setting Page   *******************************/

function zoom_highslide_add_option() {
 if (function_exists('zoom_highslide_option')) {
 add_options_page('zoom_highslide', 'Zoom-HighSlide',8, 'zoom_highslide', 'zoom_highslide_option');
 }//add_options_page(page_title, menu_title, access_level/capability, file, [function]);
}
function zoom_highslide_option(){
 $options = get_option('zoom_highslide');
 if (isset($_POST['update_setting'])) {
 $options['widthRestriction'] = $_POST['widthRestriction'];
 $options['heightRestriction'] = $_POST['heightRestriction'];
 $options['show_interval'] = $_POST['show_interval'];
 $options['controler_position'] = $_POST['controler_position'];
 $options['background_opacity'] = $_POST['background_opacity'];
 update_option('zoom_highslide', $options);
 echo '<div id="message"><p>';
 echo 'Setting Updated...';
 echo '</p></div>';
 }
 else if (isset($_POST['set_default'])) {
 $options['widthRestriction'] = '640';
 $options['heightRestriction'] = '1000';
 $options['show_interval'] = 5000;
 $options['controler_position'] = 'top center';
 $options['background_opacity'] = 0.8;
 update_option('zoom_highslide', $options);
 echo '<div id="message"><p>';
 echo 'Default setting loaded...';
 echo '</p></div>';
 }
?>
<div>
<h2>Zoom HighSlide Option</h2>
<form method="post">
 <fieldset name="set_widthRestriction">
 <p style="font-weight:bold">Width Restriction(e.g 640) :
 <input type="text" name="widthRestriction" size="20" value="<?php echo $options['widthRestriction'];?>"/ >
 </p>
 </fieldset>
 <fieldset name="set_heightRestriction">
 <p style="font-weight:bold">Height Restriction(e.g 1000) :
 <input type="text" name="heightRestriction" size="20" value="<?php echo $options['heightRestriction'];?>"/ >
 </p>
 </fieldset>

 <fieldset name="set_interval">
 <p style="font-weight:bold">Show Interval(e.g 4000) :
 <input type="text" name="show_interval" size="20" value="<?php echo $options['show_interval'];?>"/ >
 </p>
 </fieldset>

 <fieldset name="set_controlerPosition">
 <p style="font-weight:bold">Controler Position(e.g top center) :
 <input type="text" name="controler_position" size="20" value="<?php echo $options['controler_position'];?>"/ >
 </p>
 </fieldset>

 <fieldset name="set_dimmingOpacity">
 <p style="font-weight:bold">Background Opacity(0 ~ 1) :
 <input type="text" name="background_opacity" size="20" value="<?php echo $options['background_opacity'];?>"/ >
 </p>
 </fieldset>

 <div>
 <input type="submit" name="set_default" value="Load Default" />
 <input type="submit" name="update_setting" value="Update Setting" />
 </div>
</form>
</div>
<?php
}
add_action('admin_menu', 'zoom_highslide_add_option');

/*******************************  HighSlide Init   *******************************/

function zoom_highslide_javascript() {
 if ( !function_exists('wp_enqueue_script') || is_admin() ) return;
 wp_enqueue_script('prototype');
 wp_enqueue_script('scriptaculous-effects');
}

add_action('init', 'zoom_highslide_javascript');

function zoom_highslide_init() {
 $url = get_bloginfo('wpurl');
 $options = get_option('zoom_highslide');
?>
 <link rel="stylesheet" href="<?php echo $url; ?>/wp-content/plugins/zoom-highslide/highslide.css" type="text/css" media="screen" />
 <!--[if lte IE 6]>
 <link rel="stylesheet" href="<?php echo $url; ?>/wp-content/plugins/zoom-highslide/highslide-ie6.css" type="text/css" media="screen" />
 <![endif]-->
 <script type="text/javascript" src="<?php echo $url; ?>/wp-content/plugins/zoom-highslide/js/highslide-full.packed.js"></script>
 <script type="text/javascript">
 hs.graphicsDir = '<?php echo $url; ?>/wp-content/plugins/zoom-highslide/graphics/';
 hs.align = 'center';
 hs.transitions = ['expand', 'crossfade'];
 hs.outlineType = 'rounded-white';
 hs.wrapperClassName = 'controls-in-heading';
 hs.showCredits=false;
 hs.fadeInOut = true;
 hs.dimmingOpacity = <?php echo $options['background_opacity'];?>;

 // Add the controlbar
 if (hs.addSlideshow) hs.addSlideshow({
 //slideshowGroup: 'group1',
 interval: <?php echo $options['show_interval'];?>,
 repeat: false,
 useControls: true,
 fixedControls: false,
 overlayOptions: {
 opacity: 1,
 position: <?php echo '\''.$options['controler_position'].'\'' ?>,
 hideOnMouseOut: true
 }
 });
</script>

<?php
}
add_action('wp_head', 'zoom_highslide_init');

/*******************************  Photo Zoom Init   *******************************/
function wp_zoom_init() {
 $url = get_bloginfo('wpurl');
 $options = get_option('zoom_highslide');
?>

 <script type="text/javascript">
 var widthRestriction = <?php echo $options['widthRestriction'];?>;
 var heightRestriction = <?php echo $options['heightRestriction'];?>;
 </script>
 <script type="text/javascript" src="<?php echo $url; ?>/wp-content/plugins/zoom-highslide/js/zoom.js"></script>

<?php
}
add_action('wp_head', 'wp_zoom_init');

function wp_zoom($string) {
 $pattern = '/(<img(.*?)src="([^"]*.)'.IMAGE_FILETYPE.'"(.*?)\>)/ie';
 $replacement = 'stripslashes("<a\2href=\"\3\4\" class=\"highslide\" onclick=\"return hs.expand(this)\"><img src=\"\3\4\" \5></a>")';
 return preg_replace($pattern, $replacement, $string);
}

add_filter('the_excerpt', 'wp_zoom');
add_filter('the_content', 'wp_zoom');

?>

&amp;nbsp;

&amp;nbsp;

PHP Scripts for pixofcake Image Handling

pixofcake is a PHP image manipulation class. It supports resizing, alpha blending, cutting and much more.

 

 

<?php
 /**
 * Class PixOfCake
 * @author : Jay Salvat - http://jaysalvat.com
 *
 * Classe de gestion d'images
 *
 * - Exemple basique
 *         $Pix = new PixOfCake('picture.jpg');
 *        $Pix->size(200, 300)->rotate(40)->save()->show();
 *
 * - Exemple avec cache
 *         $Pix = new PixOfCake('picture.jpg', new PixOfCakeCache($param));
 *        $Pix->size(200, 300)->rotate(40)->show();
 */

class PixOfCake {
 public     $width, $height, $mime, $path;
 private $image, $backup, $data;
 private $background;

 private $Cache;

 const MIDDLE     = 'middle';
 const TOP         = 'top';
 const BOTTOM     = 'bottom';
 const LEFT         = 'left';
 const RIGHT     = 'right';

 public function __construct($path_or_data, PixOfCakeCache $Cache = null) {
 if(!function_exists('imagecreatetruecolor')) {
 throw new PixOfCakeException('Librairie GD introuvable');
 }

 if(file_exists($path_or_data)) {
 $this->path = $path_or_data;
 $this->data = null;
 } else if (imagecreatefromstring($path_or_data)) {
 $this->path = null;
 $this->data = $path_or_data;
 } else {
 throw new PixOfCakeException('Données image illisibles');
 }

 if ($Cache) {
 $this->Cache = $Cache;
 if ($this->Cache->check($this)) {
 return;
 }
 }

 if($image = @imagecreatefromstring($this->data)) {
 $mime = 'image/png';
 } else {
 $info = getimagesize($this->path);
 $mime = $info['mime'];
 switch($mime) {
 case 'image/png' :
 $image = imagecreatefrompng($this->path);
 break;
 case 'image/jpeg':
 $image = imagecreatefromjpeg($this->path);
 break;
 default:
 throw new PixOfCakeException('Format inconnu');
 break;
 }
 }

 $this->image    = $image;
 $this->backup    = $image;
 $this->width    = imagesx($image);
 $this->height    = imagesy($image);
 $this->mime        = $mime;
 $this->Cache     = $Cache;
 }

 public function rotate($angle) {
 if(!$this->image) {
 return $this;
 }

 $this->image = imagerotate($this->image, $angle, $this->background, true);
 imagealphablending($this->image, false);
 imagesavealpha($this->image, true);

 $this->width     = imagesx($this->image);
 $this->height     = imagesy($this->image);

 return $this;
 }

 public function maxSize($max) {
 if(!$this->image) {
 return $this;
 }

 if ($this->width > $this->height) {
 return $this->size($max);
 } else {
 return $this->size(null, $max);
 }
 }

 public function size($width, $height = null) {
 if(!$this->image) {
 return $this;
 }

 if(!$height &amp;&amp; $width) {
 $height = $this->height * $width / $this->width;
 }
 if($height &amp;&amp; !$width) {
 $width    = $this->width * $height / $this->height;;
 }

 $temp = $this->getCanvas($width, $height);
 imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);

 $this->width     = $width;
 $this->height     = $height;
 $this->image     = $temp;
 return $this;
 }

 public function width($width) {
 if(!$this->image) {
 return $this;
 }
 return $this->size($width);
 }

 public function height($height) {
 if(!$this->image) {
 return $this;
 }
 return $this->size(null, $height);
 }

 public function crop($x, $y, $width, $height) {
 if(!$this->image) {
 return $this;
 }

 $temp = $this->getCanvas($width, $height);
 imagecopy($temp, $this->image, 0, 0, $x, $y, $width, $height);

 $this->width     = $width;
 $this->height     = $height;
 $this->image     = $temp;
 return $this;
 }

 public function thumbnail($width, $height = null, $mode = null) {
 if(!$this->image) {
 return $this;
 }

 if (!$height) {
 $height = $width;
 }

 if (!$mode &amp;&amp; is_string($height)) {
 $mode     = $height;
 $height = $width;
 }

 if (isset($mode)) {
 if ($this->width >= $this->height)    {
 if ($width <= $height) {
 $w = $this->width / ($this->height / $height);
 $h = $height;
 } else {
 $w = $width;
 $h = $this->height / ($this->width / $width);
 }
 if ($mode == PixOfCake::LEFT) {
 $left = 0;
 } else if ($mode == PixOfCake::RIGHT) {
 $left = -($w - $width);
 } else {
 $left = -(($w - $width) / 2);
 }
 $top = 0;
 } else {
 if ($width <= $height) {
 $w = $width;
 $h = $this->height / ($this->width / $width);
 } else {
 $w = $this->width / ($this->height / $height);
 $h = $height;
 }
 if ($mode == PixOfCake::TOP) {
 $top = 0;
 } else if ($mode == PixOfCake::BOTTOM) {
 $top = -($h - $height);
 } else{
 $top = -(($h - $height) / 2);
 }
 $left = 0;
 }
 } else {
 if ($this->width >= $this->height)    {
 $w         = $width;
 $h         = $this->height / ($this->width / $width);
 $left     = 0;
 $top     = -(($h - $height) / 2);
 } else {
 $w         = $this->width / ($this->height / $height);
 $h         = $height;
 $left     = -(($w - $width) / 2);
 $top     = 0;
 }
 }

 $temp = $this->getCanvas($width, $height);
 imagecopyresampled($temp, $this->image, $left, $top, 0, 0, $w, $h, $this->width, $this->height);

 $this->width     = $width;
 $this->height     = $height;
 $this->image     = $temp;

 return $this;
 }

 public function save($path, $quality = 80) {
 if(!$this->image) {
 return $this;
 }

 switch(strtolower(pathinfo($path, PATHINFO_EXTENSION))) {
 case 'png' :
 $success = imagepng($this->image, $path);
 break;
 case 'jpeg': case 'jpg' :
 $success = imagejpeg($this->image, $path, $quality);
 break;
 default:
 throw new PixOfCakeException('Format inconnu');
 break;
 }
 if (!$success) {
 throw new PixOfCakeException("L'image (ou son cache) n'a pu être sauvegardé");
 }
 return $this;
 }

 public function show($format = null, $quality = 80, $header = true) {
 if(!$this->image) {
 return $this;
 }

 if (is_int($format)) {
 $quality = $format;
 $format = $this->mime;
 } else if (!$format) {
 $format = $this->mime;
 }
 if ($header) {
 header("Content-type: ".$format);
 }

 switch($format) {
 case 'image/png' :
 imagepng($this->image, null);
 break;
 case 'image/jpeg':
 imagejpeg($this->image, null, $quality);
 break;
 default:
 throw new PixOfCakeException('Format inconnu');
 break;
 }

 if ($this->Cache) {
 $this->Cache->save($this);
 }

 return $this;
 }

 public function data($format = null, $quality = 80) {
 ob_start();
 $this->show($format, $quality, false);
 $data = ob_get_contents();
 ob_end_clean();
 return $data;
 }

 public function restore() {
 if(!$this->image) {
 return $this;
 }

 $this->image = $this->backup;
 return $this;
 }

 public function destroy() {
 if(!$this->image) {
 return $this;
 }

 imagedestroy($this->image);
 imagedestroy($this->backup);
 }

 public function background($color, $alpha = 0) {
 if(!$this->image) {
 return $this;
 }

 $color = str_replace('#', '', $color);
 $r = hexdec(substr($color, 0, 2));
 $g = hexdec(substr($color, 2, 2));
 $b = hexdec(substr($color, 4, 2));
 $this->background = imagecolorallocatealpha($this->image, $r, $g, $b, $alpha);
 return $this;
 }

 private function getCanvas($width, $height) {
 $canvas = imagecreatetruecolor($width, $height);

 imagefill($canvas, 0, 0, $this->background);
 imagealphablending($canvas, false);
 imagesavealpha($canvas, true);

 return $canvas;
 }

 public function __toString() {
 return $this->data();
 }
}

class PixOfCakeCache {
 private $path, $file;
 private $folder = 'cache/';

 public function __construct($file = null, $data = array()) {
 $this->file = $file;
 $this->namespace($data);
 }

 public function namespace($data = array()) {
 if (!empty($data)) {
 ksort($data);
 $values = '';
 foreach($data as $k => $v) {
 $values .= $k.':'.$v.':';
 }
 $prefix = md5($values);
 $this->computePath($this->folder, $prefix.$this->file);
 }
 return $this;
 }

 public function valid($file) {
 if (file_exists($file) &amp;&amp; file_exists($this->path)) {
 if (filemtime($this->path) > filemtime($file)) {
 return true;
 }
 }
 return false;
 }

 public function check(PixOfCake $PixOfCake) {
 if (!$this->file) {
 $this->computePath($this->folder, $PixOfCake->path);
 }
 if ($this->valid($PixOfCake->path)) {
 $this->show();
 return true;
 } else {
 $this->destroy();
 return false;
 }
 }

 public function show() {
 $PixOfCake = new PixOfCake($this->path);
 $PixOfCake->show()->destroy();
 return $this;
 }

 public function save(PixOfCake $PixOfCake) {
 try {
 $PixOfCake->save($this->path)->destroy();
 } catch(PixOfCakeException $e) {
 throw new PixOfCakeCacheException('Cache impossible à écrire');
 }
 return $this;
 }

 public function destroy() {
 if (file_exists($this->path)) {
 unlink($this->path);
 }
 return $this;
 }

 public function folder($folder) {
 if (!is_dir($folder)) {
 throw new PixOfCakeCacheException("Le dossier de Cache n'existe pas");
 }
 $this->computePath($folder, $this->file);
 return $this;
 }

 private function computePath($folder, $file) {
 $this->folder     = $folder;
 $this->file     = $file;
 $this->path     = str_replace('//', '/', $folder."/".str_replace('/', '-', $file));
 return $this;
 }
}

class PixOfCakeException extends Exception {}
class PixOfCakeCacheException extends Exception {}
?>

&amp;nbsp;

&amp;nbsp;

PHP Scripts for Imager Image Handling

This PHP script can be used to perform several operations to manipulate images. The main class can perform many types of image manipulation operations, such as resize images, add alpha channel, flip, rotate, add watermark, apply effects like blur, darkness, brightness, contrast, gamma, gray scale, negate, sepia, sketch, smooth, emboss, edge detection, sharpen, soften, and other types of convolution.

 

<?php
class UploadComponent extends Object {

 var $imageData = array();
 var $destinationDir = NULL;
 var $thumbDestinationDir = NULL;
 var $imageSize = array(500,500);
 var $cropImageSize = array(90,90);
 var $tag = 'width';
 var $imageExt = array('jpg','gif','png','bmp','jpeg');


 function initialize($arr)
 {
 $this->imageData = $arr;
 }

 function isImageFile()
 {
 $ext = $this->imageExtension();

 if(in_array(strtolower($ext),$this->imageExt))
 {
 return true;
 }
 else
 {
 return false;
 }
 }

 function isValidImage()
 {
 if($this->imageData['error'] == 0 &amp;&amp; $this->imageData['name'] <> '')
 {
 if($this->isImageFile())
 {
 return true;
 }
 else
 {
 return false;
 }
 }
 else
 {
 return false;
 }
 }

 function imageExtension()
 {
 return trim(substr($this->imageData['name'],strpos($this->imageData['name'],'.')+1,strlen($this->imageData['name'])));
 }

 function upload($thumb=false)
 {
 $this->__upload($this->destinationDir,$this->imageSize[0],$this->imageSize[1]);
 if($thumb)
 {
 $this->__upload($this->thumbDestinationDir,$this->cropImageSize[0],$this->cropImageSize[1]);
 }
 }

 function __upload($filethumb,$Twidth,$Theight)
 {
 list($width,$height,$type,$attr)=getimagesize($this->imageData['tmp_name']);
 switch($type)
 {
 case 1:
 $img = imagecreatefromgif($this->imageData['tmp_name']);
 break;
 case 2:
 $img=imagecreatefromjpeg($this->imageData['tmp_name']);
 break;
 case 3:
 $img=imagecreatefrompng($this->imageData['tmp_name']);
 break;
 }

 if($this->tag == "width") //width contraint
 {
 $Theight=round(($height/$width)*$Twidth);
 }
 elseif($this->tag == "height") //height constraint
 {
 $Twidth=round(($width/$height)*$Theight);
 }
 else
 {
 if($width > $height)
 $Theight=round(($height/$width)*$Twidth);
 else
 $Twidth=round(($width/$height)*$Theight);
 }
 $thumb=imagecreatetruecolor($Twidth,$Theight);

 if(imagecopyresampled($thumb,$img,0,0,0,0,$Twidth,$Theight,$width,$height))
 {
 switch($type)
 {
 case 1:
 imagegif($thumb,$filethumb);
 break;
 case 2:
 imagejpeg($thumb,$filethumb,100);
 break;
 case 3:
 imagepng($thumb,$filethumb);
 break;
 }
 chmod($filethumb,0666);
 return true;
 }
 }
}
?>

&amp;nbsp;

&amp;nbsp;

PHP Image Upload Component Image Handling

Image Upload Component can be used to resize and process uploaded image files. It can check an uploaded file whether it has the accepted image file name extensions. This script can generate an image thumbnail, by resizing the big image, and move the file to a new directory.

 

<?php
class UploadComponent extends Object {

 var $imageData = array();
 var $destinationDir = NULL;
 var $thumbDestinationDir = NULL;
 var $imageSize = array(500,500);
 var $cropImageSize = array(90,90);
 var $tag = 'width';
 var $imageExt = array('jpg','gif','png','bmp','jpeg');


 function initialize($arr)
 {
 $this->imageData = $arr;
 }

 function isImageFile()
 {
 $ext = $this->imageExtension();

 if(in_array(strtolower($ext),$this->imageExt))
 {
 return true;
 }
 else
 {
 return false;
 }
 }

 function isValidImage()
 {
 if($this->imageData['error'] == 0 &amp;&amp; $this->imageData['name'] <> '')
 {
 if($this->isImageFile())
 {
 return true;
 }
 else
 {
 return false;
 }
 }
 else
 {
 return false;
 }
 }

 function imageExtension()
 {
 return trim(substr($this->imageData['name'],strpos($this->imageData['name'],'.')+1,strlen($this->imageData['name'])));
 }

 function upload($thumb=false)
 {
 $this->__upload($this->destinationDir,$this->imageSize[0],$this->imageSize[1]);
 if($thumb)
 {
 $this->__upload($this->thumbDestinationDir,$this->cropImageSize[0],$this->cropImageSize[1]);
 }
 }

 function __upload($filethumb,$Twidth,$Theight)
 {
 list($width,$height,$type,$attr)=getimagesize($this->imageData['tmp_name']);
 switch($type)
 {
 case 1:
 $img = imagecreatefromgif($this->imageData['tmp_name']);
 break;
 case 2:
 $img=imagecreatefromjpeg($this->imageData['tmp_name']);
 break;
 case 3:
 $img=imagecreatefrompng($this->imageData['tmp_name']);
 break;
 }

 if($this->tag == "width") //width contraint
 {
 $Theight=round(($height/$width)*$Twidth);
 }
 elseif($this->tag == "height") //height constraint
 {
 $Twidth=round(($width/$height)*$Theight);
 }
 else
 {
 if($width > $height)
 $Theight=round(($height/$width)*$Twidth);
 else
 $Twidth=round(($width/$height)*$Theight);
 }
 $thumb=imagecreatetruecolor($Twidth,$Theight);

 if(imagecopyresampled($thumb,$img,0,0,0,0,$Twidth,$Theight,$width,$height))
 {
 switch($type)
 {
 case 1:
 imagegif($thumb,$filethumb);
 break;
 case 2:
 imagejpeg($thumb,$filethumb,100);
 break;
 case 3:
 imagepng($thumb,$filethumb);
 break;
 }
 chmod($filethumb,0666);
 return true;
 }
 }
}
?>

&amp;nbsp;

PHP Scripts for libgravatar Image Handling

libgravatar is a PHP image handling script designed especially for the Gravatar handling, it takes the e-email of a person and generates an URL for displaying people images stored in the Gravatar site. Image dimensions and rating are configurable parameters.

 

<?php

class Gravatar{
 var $email;
 var $size;
 var $rating;
 var $default;

 function getGravatar(){
 /* if not set to default var */
 if (empty($this->rating)) $this->rating="G";
 if (empty($this->size)) $this->size="40";
 //check email
 if(!preg_match('/^[\w\.\-]+@\w+[\w\.\-]*?\.\w{1,4}$/', $this->email)){
 die ("Email inserita non correttamente");
 }

 $grav_url = "http://www.gravatar.com/avatar.php?
 gravatar_id="
.md5(strtolower($this->email)).
 "&amp;default=".urlencode($this->default)."&amp;size=".$this->size;

 return $grav_url;

 }
}


?>

&amp;nbsp;