Monday, 3 February 2014

Create Thumbnail From Animated GIF


Create Thumbnail From Animated GIF

<?php
try
{
    
/*** Read in the animated gif ***/
    
$animation = new Imagick("animation.gif");

    
/*** Loop through the frames ***/
    
foreach ($animation as $frame)
    {
        
/*** Thumbnail each frame ***/
        
$frame->thumbnailImage(100100);
   
        
/*** Set virtual canvas size to 100x100 ***/
        
$frame->setImagePage(10010000);
    }

    
/*** Write image to disk. Notice writeImages instead of writeImage ***/
    
$animation->writeImages("animation_thumbnail.gif");

    echo 
"Images written";
}
catch(
Exception $e)
{
    echo 
$e->getMessage();
}
?>

Create Thumbnail With GD

Create Thumbnail With GD

In this example, the image is a JPG but other formats can be used in the same manner with imageCreateFromGif and imageGif etc. Note the use of imageCopyResampled to give better image quality than imageCopyResized.

<?php

    error_reporting
(E_ALL);

    
$width 80;

    
/*** the image file to thumbnail ***/
    
$image 'spork.jpg';

    if(!
file_exists($image))
    {
        echo 
'No file found';
    }
    else
    {
        
/*** image info ***/
        
list($width_orig$height_orig$image_type) = getimagesize($image);

        
/*** check for a supported image type ***/
        
if($image_type !== 2)
        {
            echo 
'invalid image';
        }
        else
        {
            
/*** thumb image name ***/
            
$thumb 'thumb.jpg';

            
/*** maintain aspect ratio ***/
            
$height = (int) (($width $width_orig) * $height_orig);

            
/*** resample the image ***/
            
$image_p imagecreatetruecolor($width$height);
            
$image imageCreateFromJpeg($image);
            
imagecopyresampled($image_p$image0000$width$height$width_orig$height_orig);

            
/*** write the file to disc ***/
            
if(!is_writeable(dirname($thumb)))
            {
                echo 
'unable to write image in ' dirname($thumb);
            }
            else
            {
                
imageJpeg($image_p$thumb100);
            }
        }
    }
?>

Underscore To Camel Case

<?php/**
* Convert strings with underscores into CamelCase
*
* @param    string    $string    The string to convert
* @param    bool    $first_char_caps    camelCase or CamelCase
* @return    string    The converted string
*
*/
function underscoreToCamelCase$string$first_char_caps false)
{
    if( 
$first_char_caps == true )
    {
        
$string[0] = strtoupper($string[0]);
    }
    
$func create_function('$c''return strtoupper($c[1]);');
    return 
preg_replace_callback('/_([a-z])/'$func$string);
}
?>
<?php
    $str 
'this_is_under_score_word';
    echo 
underscoreToCamelCase$str);?>

Read a File line by line

Read Line From File

<?php/**
 *
 * Read a line number from a file
 *
 * @param    string    $file    The path to the file
 * @param    int    $line_num    The line number to read
 * @param    string    $delimiter    The character that delimits lines
 * @return    string    The line that is read
 *
 */
function readLine($file$line_num$delimiter="\n")
{
    
/*** set the counter to one ***/
    
$i 1;

    
/*** open the file for reading ***/
    
$fp fopen$file'r' );

    
/*** loop over the file pointer ***/
    
while ( !feof $fp) )
    {
        
/*** read the line into a buffer ***/
        
$buffer stream_get_line$fp1024$delimiter );
        
/*** if we are at the right line number ***/
        
if( $i == $line_num )
        {
            
/*** return the line that is currently in the buffer ***/
            
return $buffer;
        }
        
/*** increment the line counter ***/
        
$i++;
        
/*** clear the buffer ***/
        
$buffer '';
    }
    return 
false;
}
?>
<?php/*** make sure the file exists ***/$file 'my_file.txt';

if( 
file_exists$file ) && is_readable$file ) )
{
    echo 
readLine($file6);
}
else
{
    echo 
"Cannot read from $file";
}
?>
On PHP 5 and later versions
<?php/*** the file to read ***/$file 'foo.txt';

        
/**
 *
 * Read a line number from a file
 *
 * @param    string    $file    The path to the file
 * @param    int    $line_num    The line number to read
 * @return    string    The line that is read
 *
 */
function readLine$file$line_number )
{
        
/*** read the file into the iterator ***/
        
$file_obj = new SplFileObject$file );

        
/*** seek to the line number ***/
        
$file_obj->seek$line_number );

        
/*** return the current line ***/
        
return $file_obj->current();
}

echo 
readLine$file345678 );?>

Calculate Age With PHP

Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered. Here several solutions are put forward, each nicer than the previous.

With strtotime()

<?php
/*** make sure this is set ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$age 0;
        while( 
$tdate $dob strtotime('+1 year'$dob))
        {
                ++
$age;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob strtotime("april 20 1961");
/*** another date ***/$tdate strtotime("june 2 2009");
/*** show the date ***/echo getAge$dob$tdate );
?>

Using the DateTime Class

The PHP DateTime class allow a little neater code by providing an Object Oriented interface to date functions. By passing a DateInterval object to the DateTime class the DateTime object can be increment 1 year on each iteration until it reaches the target date. The DateTime::add() method requires PHP >= 5.3.
<?php
/*** set the default timezone ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$dob = new DateTime$dob );
        
$age 0;
        
$now = new DateTime$tdate );
        while( 
$dob->add( new DateInterval('P1Y') ) < $now )
        {
                
$age++;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob "April 20 1961";
/*** another date ***/$tdate "21-04-2009";
/*** show the date ***/echo getAge$dob$tdate );
?>

PHP Date Validation

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to checkdate.

<?php
    /**
    *
    * Validate a date
    *
    */
    function validateDate( $date, $format='YYYY-MM-DD')
    {
        switch( $format )
        {
            case 'YYYY/MM/DD':
            case 'YYYY-MM-DD':
            list( $y, $m, $d ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYY/DD/MM':
            case 'YYYY-DD-MM':
            list( $y, $d, $m ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'DD-MM-YYYY':
            case 'DD/MM/YYYY':
            list( $d, $m, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'MM-DD-YYYY':
            case 'MM/DD/YYYY':
            list( $m, $d, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYYMMDD':
            $y = substr( $date, 0, 4 );
            $m = substr( $date, 4, 2 );
            $d = substr( $date, 6, 2 );
            break;

            case 'YYYYDDMM':
            $y = substr( $date, 0, 4 );
            $d = substr( $date, 4, 2 );
            $m = substr( $date, 6, 2 );
            break;

            default:
            throw new Exception( "Invalid Date Format" );
        }
        return checkdate( $m, $d, $y );
    }


   echo validateDate( '2007-04-21' ) ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY-DD-MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY/DD/MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '21/4/2007', 'DD/MM/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '4/21/2007', 'MM/DD/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '20070421', 'YYYYMMDD' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '04212007', 'YYYYDDMM' )  ? 'good'. "\n" : 'bad' . "\n";

?>

Verify Age limit With PHP Datetime

Verify Age Limit With PHP Datetime

This small script shows how to check a person is of a given age. Buy using the PHP DateTime class, php is able to account for dates at a system level.

<?php/**
*
* Check minimum age. Defaults to 18 years
*
*/
function validate_age$dob$min_age=18 ){
        
$dob     = new DateTime$dob );
        
$min_age = new DateTime'now - ' $min_age 'years' );
        return 
$dob <= $min_age;
}
// the person must be at least 21 years of age$age 21;// persons date of birth (dd-mm-yyyy)$dob '20-4-1981';
if( 
validate_age$dob$age ) === false ){
    echo 
'Person is not 21 years old';
}else{
    echo 
'Person is 21 or over';
}
?>