Monday, May 25, 2009

Resize Image in PHP


function resize_jpg($inputFilename, $new_side){
$imagedata = getimagesize($inputFilename);
$w = $imagedata[0];
$h = $imagedata[1];

if ($h > $w) {
$new_w = ($new_side / $h) * $w;
$new_h = $new_side;
} else {
$new_h = ($new_side / $w) * $h;
$new_w = $new_side;
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
$image = ImageCreateFromJpeg($inputFilename);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $imagedata[0], $imagedata[1]);
return $im2;
}

?>

Format File Size

function GetFileSize($nBytes)
{
if ($nBytes >= pow(2,40))
{
$strReturn = round($nBytes / pow(1024,4), 2);
$strSuffix = "TB";
}
elseif ($nBytes >= pow(2,30))
{
$strReturn = round($nBytes / pow(1024,3), 2);
$strSuffix = "GB";
}
elseif ($nBytes >= pow(2,20))
{
$strReturn = round($nBytes / pow(1024,2), 2);
$strSuffix = "MB";
}
elseif ($nBytes >= pow(2,10))
{
$strReturn = round($nBytes / pow(1024,1), 2);
$strSuffix = "KB";
}
else
{
$strReturn = $nBytes;
$strSuffix = "Byte";
}

if ($strReturn == 1)
{
$strReturn .= " " . $strSuffix;
}
else
{
$strReturn .= " " . $strSuffix . "s";
}

return $strReturn;
}
?>

Get the list of folders and/or Files


function listFolder($folder, $types = 0)
{
$functions = array(
1 => 'is_dir',
2 => 'is_file'
);

$folderList = array();

foreach( glob( "$folder/*" ) as $currentItem )
{
if( $types == 1 or $types == 2 )
{
if( $functions[$types]($currentItem) )
$folderList[] = basename($currentItem);
}
else $folderList[] = basename($currentItem);
}

return $folderList;
}

?>

How to Strip file Extension

function strip_ext($name)
{
$ext = strrchr($name, '.');

if($ext !== false)
{
$name = substr($name, 0, -strlen($ext));
}

return $name;
}

// demonstration
$filename = 'file_name.txt';
echo strip_ext($filename)."n";

// to get the file extension, do
echo end(explode('.',$filename))."n";
?>

Simple function to read directory contents


/*
** Function: dir_list (PHP)
** Desc: Simple function to read directory contents
** Example: dir_list('data/');
** Author: Jonas John
*/

function dir_list($path){

$files = array();

if (is_dir($path)){
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file[0] == '.'){ continue; }

if (is_file($path.$file)){
$files[] = $file;
}
}
closedir($handle);
sort($files);
}

return $files;

}
?>