显示文件夹中库中的最新图像


displaying most recent images in a gallery from folder

我正在将用户使用canvas标记创建的图像保存到我网站上的文件夹中:

<?php 
$data = $_POST['img']; 
$data = str_replace('data:image/png;base64,','',$data);
$data = str_replace(' ', '+', $data);
$img = base64_decode($data);
$path = 'images/' . uniqid() . '.png';
if(file_put_contents($path, $img)){
print $path;
}else{
header("HTTP/1.1 500 Internal Server Error");
}
?>

然后在图库中显示图像:

<?php // display source code
$folder_path = 'images/';
$files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
foreach($files as $file){
echo '<img src="'.$file.'" />';    
}
?>

我希望最新的图片显示在顶部如果可能的话,一次只显示少数图像,并具有"显示更多"功能,当点击时,隐藏的元素将可见

您可以将图像的名称与时间戳一起保存在数据库(例如mysql)中,并使用top (number of records to be shown)order by (timestamp column) desc 查询最近的图像

您需要先按日期将图像排序到一个数组中,然后从数组中显示它们,如下所示:

$folder_path = 'images/';
$files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
//Images array
$images = array();
foreach($files as $key => $file) {
    //Get the modified time of the file
    $filetime = filemtime($file);
    //Add the info to an array
    $images[$key]['filepath'] = $file;
    $images[$key]['filetime'] = $filetime;
}
//Sort the array
usort($images, function($a, $b){
    return $b['filetime'] - $a['filetime'];
});
//Now you can display the images
foreach($images as $image) {
    echo '<img src="' . $image["filepath"] . '" />';
}

如果您决定先按最旧图像的顺序显示它们,那么只需在usort()函数中交换$b和$a,如下所示:

usort($images, function($a, $b){
    return $a['filetime'] - $b['filetime'];
});

请在此处查看有关usort的更多信息:http://php.net/manual/en/function.usort.php

关于"显示更多"按钮,您想了解javascript/jquery并了解如何做到这一点,恐怕这是一个需要回答的非常广泛的问题。