Title

Отображаем все картинки из директории при помощи PHP

Случилось так, что подготавливая материалы для одного из будущих постов о забавной старой MS-DOS игре, мне понадобилось сделать скриншот около 500 маленьких иконок-спрайтов, собранных все вместе рядом и в заданном количестве колонок. Искать и устанавливать специальный софт чтобы генерировать коллажи картинок было не охота, задача очень проста и решилась в два десятка строк на PHP. Выводим все найденные картинки из директории в виде таблички и задаем фон — все просто, как в 1м классе.

Подготовка

Итак, список действий для данной задачки:

  • открыть директорию;
  • отсеять все файлы что не являются картинками по расширению png, jpg, gif;
  • вывести каждый рисунок в табличке с заданным количеством колонок и цветом фона.

Для тестирования и разработки на PHP подобных скриптов всегда удобно держать под рукой сборку с локальным веб-сервером Apache+PHP. В принципе подойдет любой локальный веб-сервер, я же использую OpenServer — он бесплатен, прост в установке и настройке.

Вот самое простое решение на PHP, написанное за несколько минут:

// show images in grid $columns = 15; $background = '#DBEAF9'; $images_dir = 'images/'; $count = 1; echo ''; if(is_dir($images_dir)) < if ($h = opendir($images_dir)) < while (($file = readdir($h)) !== false) < if(preg_match("#\.(jpg|gif|png)$#i", $file)) < echo ''; $count++; if( ($count%$columns)==0 ) echo ''; > > closedir($h); > > echo '
';

Все картинки из директории, что размещена там же где и файл-скрипт, будут выведены в виде таблици с количеством колонок равным 15. Цвет фона таблици — #DBEAF9 .

Читайте также:  Нижнее подчеркивание в java

Результат

Вот что получается в результате генерации HTML кода скриптом:

Выводим картинки из директории при помощи PHP

Заключение

Вот такое простое решение простой задачи на PHP. При сборе и обработке информации, картинок и прочих ресурсов уже очень часто сталкиваюсь с подобными задачами, для которых не обязательно качать у устанавливать массу разного софта, достаточно вспомнить что под рукой есть простой и удобный инструмент — скриптовый язык программирования PHP.

Вообще любой язык программирования при умелом обращении, в целях автоматизации, может сэкономить массу времени при решении разных рутинных задач. Представьте только себе, к примеру, если бы эти 500 картинок взять и вручную по сращивать в Фотошопе — даже представить страшно сколько на это уйдет времени.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Show all images in a folder with PHP. A simple PHP tool to list all images in a folder.

tennisfar/show-all-images-in-a-folder-with-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Show all images in a folder with PHP

A simple webpage to display all images in a folder. It requires PHP.

Images will display up to a max width of 900 pixels. Images larger than 900 pixels will show their full size if you click it.

You can link to a specific image as they’re link anchored. Just click on the specific image and copy the browser URL.

This works out of the box, so you can either Git clone the repository, or download the zip.

Add ins-imgs.php and ins-imgs.css in your root folder (or wherever your index file is).

In your index HTML, insert this:

 script src pl-s">ins-imgs.php">script>

In ins-imgs.php you can find the following settings:

# Path to image folder $imageFolder = 'img/'; # Show only these file types from the image folder $imageTypes = ''; # Set to true if you prefer sorting images by name # If set to false, images will be sorted by date $sortByImageName = false; # Set to false if you want the oldest images to appear first # This is only used if images are sorted by date (see above) $newestImagesFirst = true;

Make the changes needed for your setup.

Help, bugs, pull requests, etc.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Show all images in a folder with PHP. A simple PHP tool to list all images in a folder.

tennisfar/show-all-images-in-a-folder-with-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Show all images in a folder with PHP

A simple webpage to display all images in a folder. It requires PHP.

Images will display up to a max width of 900 pixels. Images larger than 900 pixels will show their full size if you click it.

You can link to a specific image as they’re link anchored. Just click on the specific image and copy the browser URL.

This works out of the box, so you can either Git clone the repository, or download the zip.

Add ins-imgs.php and ins-imgs.css in your root folder (or wherever your index file is).

In your index HTML, insert this:

 script src pl-s">ins-imgs.php">script>

In ins-imgs.php you can find the following settings:

# Path to image folder $imageFolder = 'img/'; # Show only these file types from the image folder $imageTypes = ''; # Set to true if you prefer sorting images by name # If set to false, images will be sorted by date $sortByImageName = false; # Set to false if you want the oldest images to appear first # This is only used if images are sorted by date (see above) $newestImagesFirst = true;

Make the changes needed for your setup.

Help, bugs, pull requests, etc.

Источник

cezarderevlean / folder-img-to-html.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

how add this code to html web page?
sorry for silly question but curiosity ?

You need a server being able to run php files.

I am using jquery and javascript. Is there an alternative without using php to do this? Thanks

I think you have to use something on the server side. If you want JS, you can use Node.

ul li ul li img ul li span// close directory closedir($myDirectory); // count elements in array $indexCount = count($dirArray); ?>
  • Image' . $dirArray[$index] . ''; > > ?>
ul li ul li img ul li span// close directory closedir($myDirectory); // count elements in array $indexCount = count($dirArray); ?>
  • Image' . $dirArray[$index] . ''; > > ?>

I got the php working to display the current working directory. I have wanted to do this since 2008.

However, I also run a backup webserver from my house. I have tried about a dozen windows webservers and only found one over the year that I could get running, which may have been written by a very bright guy in 2004, called homeseries. I never was able to get the php to work on my windows home webserver (even after trying to dl php machines and installing).

I personally really, really like php for its easy learning curve, human readability, non limiting user access to their preferred fonts and layout, doesn’t limit note taking cut and paste into research notes, fast speed relative to sloggy javascript, and universal browser and universal proxy ability, even with 19x lowbandwidth accelerators which I still use to get my 140 weather products over my cell connection to keep my data down and cell bill to $5/mo per line.

On the other hand, I personally hate browsing javascripted webpages (for a myriad of reasons). I actually loathe everything javascript to its core. I have js hangups. But no choice, but to browse with it turned on, anymore and endure the page load slowdown.

Regardless of js hangups, I unfortunately need use javascript for my home web server image gallery index.html on the home server to display all images.

I don’t understand recommended the links for js way to do it here (google is silent in my results. I also don’t get this thread, which solves the problem with php. Then it is asked how to do this in javascript, without php, but then it is answered with js code that still uses php.

The best javascript I can get, so far, from the links, for a js only index.html is (which outputs only garbage ):

    ul li ul li img ul li span // Import the filesystem module 

let directory_name = «example_dir»;

// Open the directory
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf(‘/’));
//let openedDir = fs.opendirSync(directory_name);
let openedDir = dir

// Print the pathname of the directory
console.log(«\nPath of the directory:», openedDir.path);

// Get the files present in the directory
console.log(«Files Present in directory:»);

let filesLeft = true;
while (filesLeft) // Read a file as fs.Dirent object
let fileDirent = openedDir.readSync();

// If readSync() does not return null
// print its filename
if (fileDirent != null)
console.log(«Name:», fileDirent.name);

// If the readSync() returns null
// stop the loop
else filesLeft = false;
>

Источник

Оцените статью