Sorting results of a PHP Thumbnail Script - php

I found the following PHP script on the net which is taking a directory of images and creating thumbnails. This part works great, expect I've noticed the sorting is off. Best I can tell is it's using file names, I'd like to use creation date as I'm sorting a directory of images created from a security camera.
Any input and a bit (ok, a lot) of direction would be great as I don't have a lot of PHP experience, but can get around somewhat.
Thanks again for the help!
<html><head><title>Snapshots</title></head>
<body bgcolor='white'>
<?php
$folder = '.';
$dir = getcwd();
DirStat($folder, 0);
chdir($dir);
$FolderSize = ByteSize($FolderSize);
$FileCount=$FileCount-2;
?>
<h2 align=center><?php echo date('m/d/Y H:i:s') ." - $FileCount Snapshots - $FolderSize";?></h4>
<?php
$imagens='';
$dn = opendir('.');
while (false !== ($file = readdir($dn))) {
if ($file == '.' || $file =='..' || $file =='index.php' || $file =='Thumbs.db'){
//print "<a href=$file>$file</a><br>";
}else{
if (is_dir($file)){
print "<img src='/imagens/diretorio.png'> <a href='$file?dir=dirname(__FILE__)'>$file</a><br>";
}else{
$tamanho = filesize($file);
$m = 'bytes'; // M�ltiplo
if ($tamanho>1024) {
$tamanho=round($tamanho/1024,2);
$m = 'KB';
} elseif($tamanho > 1024*1024){
$tamanho = round(($tamanho/1024)/1024,2);
$m = 'MB';
}
$imagens .=OutputThumbnail($file, $tamanho, $m);
}
}
}
closedir($dn);
print '<br>'.$imagens;
function OutputThumbnail($image_file, $tamanho, $m)
{
if (file_exists($image_file))
{
$size = GetImageSize($image_file);
if ($size[0] <=64) {
$larg=$size[0];
}elseif ($size[0] > 64 && $size[0] <= 200) {
$larg=64;
}elseif ($size[0] > 201 && $size[0] < 400) {
$larg=128;
}elseif ($size[0] > 401) {
$larg=256;
}
if ($size[0] == 0) $size[0]=1;
$alt= ($larg * $size[1])/$size[0];
return "<a href=$image_file><img width=$larg height=$alt src=$image_file border=0
TITLE='$image_file - $larg x $alt - $tamanho $m'></a> ";
}
}
?>
<?php
function DirStat($directory) {
global $FolderCount, $FileCount, $FolderSize;
chdir($directory);
$directory = getcwd();
if($open = opendir($directory)) {
while($file = readdir($open)) {
if($file == '..' || $file == '.') continue;
if(is_file($file)) {
$FileCount++;
$FolderSize += filesize($file);
} elseif(is_dir($file)) {
$FolderCount++;
}
}
if($FolderCount > 0) {
$open2 = opendir($directory);
while($folders = readdir($open2)) {
$folder = $directory.'/'.$folders;
if($folders == '..' || $folders == '.') continue;
if(is_dir($folder)) {
DirStat($folder);
}
}
closedir($open2);
}
closedir($open);
}
}
function ByteSize($bytes) {
$size = $bytes / 1024;
if($size < 1024){
$size = number_format($size, 2);
$size .= 'KB';
} else {
if($size / 1024 < 1024) {
$size = number_format($size / 1024, 2);
$size .= 'MB';
} elseif($size / 1024 / 1024 < 1024) {
$size = number_format($size / 1024 / 1024, 2);
$size .= 'GB';
} else {
$size = number_format($size / 1024 / 1024 / 1024,2);
$size .= 'TB';
}
}
return $size;
}
?>

I have added a very dirty way of sorting (not efficient). Change below line to SORT_DESC or SORT_ASC in the code to sort descending or ascending.
arraySortByColumn($exifData, 'time', SORT_DESC);
Your script with added sorting functionality:
<html><head><title>Snapshots</title></head>
<body bgcolor='white'>
<?php
$folder = '.';
$dir = getcwd();
DirStat($folder, 0);
chdir($dir);
$FolderSize = ByteSize($FolderSize);
$FileCount=$FileCount-2;
?>
<h2 align=center><?php echo date('m/d/Y H:i:s') ." - $FileCount Snapshots - $FolderSize";?></h4>
<?php
$imagens='';
$exifData = array();
$dn = opendir('.');
while (false !== ($file = readdir($dn))) {
if ($file == '.' || $file =='..' || $file =='index.php' || $file =='Thumbs.db'){
//print "<a href=$file>$file</a><br>";
}else{
if (is_dir($file)){
print "<img src='/imagens/diretorio.png'> <a href='$file?dir=dirname(__FILE__)'>$file</a><br>";
}else{
$tamanho = filesize($file);
$datetime = #exif_read_data($file);
$m = 'bytes'; //
if ($tamanho>1024) {
$tamanho=round($tamanho/1024,2);
$m = 'KB';
} elseif($tamanho > 1024*1024){
$tamanho = round(($tamanho/1024)/1024,2);
$m = 'MB';
}
$exifData[] = array('time' => $datetime['FileDateTime'], 'file' => $file, 'tamanho' => $tamanho, 'm' => $m );
}
}
}
closedir($dn);
//change to SORT_DESC or SORT_ASC
arraySortByColumn($exifData, 'time', SORT_DESC);
foreach ($exifData as $value) {
$imagens .= OutputThumbnail($value['file'], $value['tamanho'], $value['m']);
}
print '<br>'.$imagens;
function arraySortByColumn(&$arr, $col, $dir = SORT_DESC) {
$sort_col = array();
foreach ($arr as $key => $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
function OutputThumbnail($image_file, $tamanho, $m)
{
if (file_exists($image_file))
{
$size = GetImageSize($image_file);
if ($size[0] <=64) {
$larg=$size[0];
}elseif ($size[0] > 64 && $size[0] <= 200) {
$larg=64;
}elseif ($size[0] > 201 && $size[0] < 400) {
$larg=128;
}elseif ($size[0] > 401) {
$larg=256;
}
if ($size[0] == 0) $size[0]=1;
$alt= ($larg * $size[1])/$size[0];
return "<a href=$image_file><img width=$larg height=$alt src=$image_file border=0
TITLE='$image_file - $larg x $alt - $tamanho $m'></a> ";
}
}
?>
<?php
function DirStat($directory) {
global $FolderCount, $FileCount, $FolderSize;
chdir($directory);
$directory = getcwd();
if($open = opendir($directory)) {
while($file = readdir($open)) {
if($file == '..' || $file == '.') continue;
if(is_file($file)) {
$FileCount++;
$FolderSize += filesize($file);
} elseif(is_dir($file)) {
$FolderCount++;
}
}
if($FolderCount > 0) {
$open2 = opendir($directory);
while($folders = readdir($open2)) {
$folder = $directory.'/'.$folders;
if($folders == '..' || $folders == '.') continue;
if(is_dir($folder)) {
DirStat($folder);
}
}
closedir($open2);
}
closedir($open);
}
}
function ByteSize($bytes) {
$size = $bytes / 1024;
if($size < 1024){
$size = number_format($size, 2);
$size .= 'KB';
} else {
if($size / 1024 < 1024) {
$size = number_format($size / 1024, 2);
$size .= 'MB';
} elseif($size / 1024 / 1024 < 1024) {
$size = number_format($size / 1024 / 1024, 2);
$size .= 'GB';
} else {
$size = number_format($size / 1024 / 1024 / 1024,2);
$size .= 'TB';
}
}
return $size;
}
?>

Related

Function php with loop

In index.php I have arrays listing folders. Function.php has code that counts the size of the folder. The code works when I type the folder name manually. I don't know how to make the code in function.php count for all folders in index.php. In index.php I made a loop foreach ($nameFolders as $index => $value) {echo $nameFolders[$index];} but it does not work in function.php $disk_used = foldersize ($nameFolders[$index]);
index.php
$nameFolders = array("nameFolder1", "nameFolder2", "nameFolder3");
foreach ($nameFolders as $index => $value) {
echo $nameFolders[$index];
}
include 'function.php';
function.php
$units = explode(' ', 'B KB MB GB');
$disk_used = foldersize($nameFolders[$index]);
$totalSize = format_size($disk_used);
function foldersize($path)
{
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/').'/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath.$t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size)
{
global $units;
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".") + 3;
return substr($size, 0, $endIndex).' '.$units[$i];
}
There are several things wrong with your code, starting with the include order. If you include (and thus declare) the functions AFTER your loop, you cannot use them inside the loop; I understand that you are trying to print all the folders with their sizes.
index.php
<?php
include_once('function.php'); // this needs to happen before.
$name_folders = array('nameFolder1', 'nameFolder2', 'nameFolder3');
// no need for key => value here if you don't use that
foreach ($name_folders as $folder) {
$disk_used = folder_size($folder);
$totalSize = format_size($disk_used);
echo "$folder: $totalSize\n";
}
function.php
<?php
$units = explode(' ', 'B KB MB GB');
function folder_size($path)
{
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/').'/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$currentFile = $cleanPath.$t;
if (is_dir($currentFile)) {
$size = folder_size($currentFile);
$total_size += $size;
} else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size)
{
global $units;
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".") + 3;
return substr($size, 0, $endIndex).' '.$units[$i];
}
Please note that this "include function.php" style of PHP is how we did it in 1999, and it's not really a modern practice. Same goes for the use of global there. Try sticking to ONE naming convention: you mix camelCase with snake_case.

copy a php file to every directory

I've a simple problem of copying a a php folder to some directories, bu the problem is I can't the solution for that, the idea is that I've an Online Manga Viewer script, and what I want to do is I want to add comments page to every chapter, the I dea that I came with, is, I create a separate comments page file and once a new chapter added the the comments file will be copied to the folder of the chapter :
Description Image:
http://i.stack.imgur.com/4wYE0.png
What I to know is how can I do it knowing that I will use Disqus commenting System.
Functions used in the script:
function omv_get_mangas() {
$mangas = array();
$dirname = "mangas/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$mangas[] = $file;
}
}
#closedir($dir);
}
sort($mangas);
return $mangas;
}
function omv_get_chapters($manga) {
global $omv_chapters_sorting;
$chapters = array();
$chapters_id = array();
$dirname = "mangas/$manga/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (is_dir($dirname . $file . '/') && ($file != ".") && ($file != "..")) {
$chapter = array();
$chapter["folder"] = $file;
$pos = strpos($file, '-');
if ($pos === false) {
$chapter["number"] = $file;
} else {
$chapter["number"] = trim(substr($file, 0, $pos - 1));
$chapter["title"] = trim(substr($file, $pos + 1));
}
$chapters_id[] = $chapter["number"];
$chapters[] = $chapter;
}
}
#closedir($dir);
}
array_multisort($chapters_id, $omv_chapters_sorting, $chapters);
return $chapters;
}
function omv_get_chapter_index($chapters, $chapter_number) {
$i = 0;
while (($i < count($chapters)) && ($chapters[$i]["number"] != $chapter_number)) $i++;
return ($i < count($chapters)) ? $i : -1;
}
function omv_get_pages($manga, $chapter) {
global $omv_img_types;
$pages = array();
$dirname = "mangas/$manga/$chapter/";
$dir = #opendir($dirname);
if ($dir) {
while (($file = #readdir($dir)) !== false) {
if (!is_dir($dirname . $file . '/')) {
$file_extension = strtolower(substr($file, strrpos($file, ".") + 1));
if (in_array($file_extension, $omv_img_types)) {
$pages[] = $file;
}
}
}
#closedir($dir);
}
sort($pages);
return $pages;
}
/*function add_chapter_comment($dirname){
$filename = $dirname.'comments.php';
if (file_exists($filename)) {
} else {
copy('comments.php', .$dirname.'comments.php');
}
}*/
function omv_get_previous_page($manga_e, $chapter_number_e, $current_page, $previous_chapter) {
if ($current_page > 1) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page - 1);
} else if ($previous_chapter) {
$pages = omv_get_pages(omv_decode($manga_e), $previous_chapter["folder"]);
return $manga_e . '/' . omv_encode($previous_chapter["number"]) . '/' . count($pages);
} else {
return null;
}
}
function omv_get_next_page($manga_e, $chapter_number_e, $current_page, $nb_pages, $next_chapter) {
if ($current_page < $nb_pages) {
return $manga_e . '/' . $chapter_number_e . '/' . ($current_page + 1);
} else if ($next_chapter) {
return $manga_e . '/' . omv_encode($next_chapter["number"]);
} else {
return null;
}
}
function omv_get_image_size($img) {
global $omv_img_resize, $omv_preferred_width;
$size = array();
$imginfo = getimagesize($img);
$size["width"] = intval($imginfo[0]);
$size["height"] = intval($imginfo[1]);
if ($omv_img_resize) {
if ($size["width"] > $omv_preferred_width) {
$size["height"] = intval($size["height"] * ($omv_preferred_width / $size["width"]));
$size["width"] = $omv_preferred_width;
}
}
return $size;
}
And thanks for all of you!
Include the following line in all of your pages in a small php statement, if it covers two folder paths, use this. Which I think in your case it does.
<?php
include('../../header.php');
?>
And then save this in the main root directory. Which in your diagram is called "Main Folder"

Proper foreach loop procedure with resizing image(s)

Only one of the thumbnail images saves to the folder of this script even though several images are uploading. I'm thinking it must be something related to the iteration of the foreach loop. This is only the resizing script posted below. Does anyone have a quick fix? Thanks
define('THUMBS_DIR', 'C: /inetpub / wwwroot / mysite / images / thumbs / ');
define('MAX_WIDTH', 90);
define('MAX_HEIGHT', 100);
if (array_key_exists('upload', $_POST))
{
$original = $_FILES['image']['tmp_name'];
foreach ($original as $number => $tmp_file)
{
$original = ($tmp_file);
}
if (!$original)
{
echo 'NoImageSelected';
}
} else {
list($width, $height, $type) = getimagesize($original);
if ($width <= MAX_WIDTH && $height <= MAX_HEIGHT)
{
$ratio = 1;
} elseif ($width > $height) {
$ratio = MAX_WIDTH/$width;
} else {
$ratio = MAX_HEIGHT/$height;
}
$imagetypes = array(' / . gif$ / ',' / . jpg$ / ',' / . jpeg$ / ',' / . png$ / ');
$name = preg_replace($imagetypes, '', basename($file[$location]));
$moved = # move_uploaded_file($original[$location], THUMBS_DIR.$file);
if ($moved)
{
$result[] = $_FILES['image']['name'].'succesfullyuploaded';
$original = $ext.$file[$location];
}else{
$result = 'Problemuploading'.$_FILES['image']['name'];
}
if ($type == 1)
{
$source = imagecreatefromgif($original);
} elseif ($type == 2) {
$source = imagecreatefromjpeg($original);
} elseif ($type == 3) {
$source = imagecreatefrompng($original);
} else {
$result = 'Cannotidentifythefiletype';
}
}
Could you be more descriptive about what you want the script to do. I think your problem could be in :
$original = ($tmp_file);
You are overwriting the variable that you use in your foreach loop.

PHP Get dimensions of images in dir

I have a huge ammount of photos that need sorting through. I need to know the dimensions of each photo in order to know or it needs re-sizing. As a programmer I'm convinced there must be a quicker way of doing this.
I got quite far. The following code reads the dir and all the sub dirs. But the moment I try to extract the dimensions the loop halts at 8% of all the pictures that need checking. Could it be PHP is not allowed to do more calculations? What is going on!?
This is how far I got:
checkDir('dir2Check');
function checkDir($dir, $level = 0) {
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (!preg_match('/\./i', $entry)) {
echo echoEntry("DIR\\", $entry, $level);
checkDir($dir.'/'.$entry, $level+1);
} else {
if ($entry != "." && $entry != ".." && $entry != ".DS_Store") {
// if I comment the next line. It loops through all the files in the directory
checkFile($entry, $dir.'/'.$entry, $level);
// this line echoes so I can check or it really read all the files in case I comment the proceeding line
//echo echoEntry("FILE", $entry, $level);
}
}
}
$level--;
closedir($handle);
}
}
// Checks the file type and lets me know what is happening
function checkFile($fileName, $fullPath, $level) {
if (preg_match('/\.gif$/i', $fullPath)) {
$info = getImgInfo(imagecreatefromgif($fullPath));
} else if (preg_match('/\.png$/i', $fullPath)) {
$info = getImgInfo(imagecreatefrompng($fullPath));
} else if (preg_match('/\.jpe?g$/i', $fullPath)){
$info = getImgInfo(imagecreatefromjpeg($fullPath));
} else {
echo "XXX____file is not an image [$fileName]<br />";
}
if ($info) {
echo echoEntry("FILE", $fileName, $level, $info);
}
}
// get's the info I need from the image and frees up the cache
function getImgInfo($srcImg) {
$width = imagesx($srcImg);
$height = imagesy($srcImg);
$info = "Dimensions:".$width."X".$height;
imagedestroy($srcImg);
return $info;
}
// this file formats the findings of my dir-reader in a readable way
function echoEntry($type, $entry, $level, $info = false) {
$output = $type;
$i = -1;
while ($i < $level) {
$output .= "____";
$i++;
}
$output .= $entry;
if ($info) {
$output .= "IMG_INFO[".$info."]";
}
return $output."<br />";
}
The following does similar to what you do, only it's using php's DirectoryIterator which in my humble opinion is cleaner and more OOP-y
<?php
function walkDir($path = null) {
if(empty($path)) {
$d = new DirectoryIterator(dirname(__FILE__));
} else {
$d = new DirectoryIterator($path);
}
foreach($d as $f) {
if(
$f->isFile() &&
preg_match("/(\.gif|\.png|\.jpe?g)$/", $f->getFilename())
) {
list($w, $h) = getimagesize($f->getPathname());
echo $f->getFilename() . " Dimensions: " . $w . ' ' . $h . "\n";
} elseif($f->isDir() && $f->getFilename() != '.' && $f->getFilename() != '..') {
walkDir($f->getPathname());
}
}
}
walkDir();
You can simply use getimagesize()
list($width, $height) = getimagesize($imgFile);

PHP: Sorting array with natsort

I have a PHP script that creates a thumbnail and lists an image gallery. The problem I'm having is that it lists it by timestamp on the server but I want it to list 'naturally'.
<?php
# SETTINGS
$max_width = 100;
$max_height = 100;
$per_page = 24;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(".") ) {
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('thumbs') ) {
mkdir('thumbs');
}
if ( ! file_exists('thumbs/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$file.'" class="zoom" rel="group">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, 'thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, 'thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, 'thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>
similair to hobodave but i would use php's built in natsort function:
uksort($output, "strnatcmp");
You're not even using an array.
Instead of echo'ing your li's as you encounter them you need to put them into an array, indexed by filename.
$output[$file] = '<li>etc</li>';
Then once your loop has completed, you'll need to use a custom function to do a natural key sort, since PHP's natsort() only works on values.
function natksort($array) {
$keys = array_keys($array);
natsort($keys);
$ret = array();
foreach ($keys as $k) {
$ret[$k] = $array[$k];
}
return $ret;
}
$output = natksort($output);
echo '<ul>';
foreach ($output as $out) {
echo $out;
}
echo '</ul>';
Edit
Wow, I found this little gem to do the sorting:
uksort($array, 'strnatcasecmp');
Credit: http://www.chipstips.com/?p=269
The trick was to put everything inside an array... I took the liberty of rewriting your getPictures() function... This one implements the sorting.
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if (!is_dir('thumbs')) {
mkdir('thumbs');
}
if ($handle = opendir(".")) {
$lightbox = rand();
$files = array();
while (($file = readdir($handle)) !== false) {
if (!is_dir($file) && ($type = getPictureType($file)) != '') {
$files[] = $file;
}
}
natsort($files);
$has_previous = $skip != 0;
$has_next = (count($files) - $skip - $per_page) > 0;
$spliceLength = min($per_page, count($files) - $skip);
$files = array_slice($files, $skip, $spliceLength);
echo '<ul id="pictures">';
foreach($files as $file) {
if (!file_exists('thumbs/' . $file)) {
$type = getPictureType($file);
makeThumb($file, $type);
}
echo '<li><a href="' . $file . '" class="zoom" rel="group">';
echo '<img src="thumbs/' . $file . '" alt="" />';
echo '</a></li>';
}
echo '</ul>';
}
}

Categories