创建无数据库PHP图像库
图库.php
<!-- (A) CSS & JS -->
<link href="gallery.css" rel="stylesheet">
<script src="gallery.js"></script>
<div class="gallery"><?php
// (B) GET LIST OF IMAGE FILES FROM GALLERY FOLDER
$dir = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
$images = glob("$dir*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
// (C) OUTPUT IMAGES
foreach ($images as $i) {
printf("<img src='gallery/%s'/>", basename($i));
}
?></div>
上面是图像库页面的全部内容
引入CSS
图库.css
/* (A) GALLERY CONTAINER */
/* (A1) ON BIG SCREENS */
.gallery {
display: grid;
grid-template-columns: repeat(3, auto); /* 3 IMAGES PER ROW */
grid-gap: 10px;
max-width: 1200px;
margin: 0 auto; /* HORIZONTAL CENTER */
}
/* (A2) ON SMALL SCREENS */
@media screen and (max-width: 640px) {
.gallery {
grid-template-columns: repeat(2, auto); /* 2 IMAGES PER ROW */
}
}
/* (B) THUMBNAILS */
.gallery img {
width: 100%;
height: 200px;
/* FILL, CONTAIN, COVER, SCALE-DOWN : USE WHICHEVER YOU LIKE */
object-fit: cover;
}
.gallery img:fullscreen { object-fit: contain; }
/* (X) DOES NOT MATTER */
body, html {
padding: 0;
margin: 0;
}
加载Js全屏图像
图库.js
window.addEventListener("DOMContentLoaded", () => {
// (A) GET ALL IMAGES
var all = document.querySelectorAll(".gallery img");
// (B) CLICK ON IMAGE TO TOGGLE FULLSCREEN
if (all.length>0) { for (let img of all) {
img.onclick = () => {
// (B1) EXIT FULLSCREEN
if (document.webkitFullscreenElement || document.fullscreenElement) {
if (document.exitFullscreen) { document.exitFullscreen(); }
else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); }
}
// (B2) ENGAGE FULLSCREEN
else {
if (img.requestFullscreen) { img.requestFullscreen(); }
else if (img.webkitRequestFullscreen) { img.webkitRequestFullscreen(); }
}
});
}}
});
这里已经可以引入并生成画廊,如果你还想
文件名作为图像标题
标题库.php
foreach ($images as $i) {
$img = basename($i);
$caption = substr($img, 0, strrpos($img, "."));
printf("<figure><img src='gallery/%s'/><figcaption>%s</figcaption></figure>", $img, $caption);
}
进行图像排序
按日期排序
usort($images, function($file1, $file2) {
// NEWEST FILE FIRST
return filemtime($file2) <=> filemtime($file1);
// OLDEST FILE FIRST
// return filemtime($file1) <=> filemtime($file2);
});
按文件名排序
<h1>CATEGORY A</h1>
<div class="gallery"><?php
$images = glob(FOLDER A);
foreach ($images as $i) { printf("<img ... />"); }
?></div>
<h1>CATEGORY B</h1>
<div class="gallery"><?php
$images = glob(FOLDER B);
foreach ($images as $i) { printf("<img ... />"); }
?></div>
现在只需将图像放入不同的类别文件夹中,然后重复"获取文件列表并输出HTML"即可