Скрипт галерея на php

An image gallery can show a large number of photos on an online site efficiently. The gallery lets the user view all images that occur all over the site from one place.

There are three ways you can create an image gallery. The first one manually adds all images to your page and makes an image gallery. The second way is to store the image file names into the database. And the last one is from a directory. In this guide, you will see how you can create a dynamic image gallery from a directory in PHP.

Prerequisite

  • Isotope – To make our image gallery Pinterest type resposive masonry grid. Because Images may be of different sizes.
  • Lightbox2 – This is a simple lightbox plugin. We need to also add this features to our image gallery.
  • Bootstrap 4 (Optional) – This is optional. If you want to use Bootstrap to your site, you can use it.

Include CSS and JS:

Here we are using two plugins i.e. Isotope and Lightbox2. You can either download and use the files directly on your server or use the CDN version. Lightbox2 needs some image files. That’s why I am not going to use its CDN version. For Isotope, we will use its CDN version. First, check the directory structure.

image gallery structure

CSS

JS

We are going to use our all scripting files before the end of the tag.

Basic HTML Structure

This is a basic HTML structure. With PHP we will automatically show all the images in a folder in this structure.

  • .gallery-list will wrap the all image items.
  • .gallery-item denotes each image item from folder.
  • Suppose, images folder has a file named 1.jpeg that is high resolution picture
  • The thumb folder, inside the images will store the same image, but in low resolution for fast loading.
  • In data-lightbox=»gallery» , you can use what ever you want instead of gallery.
  • Basically it will group all the pictures. And when there is a slideshow after clicking on an image, it will only show images whose group id is gallery.

Apply CSS

 .gallery-item < width: 20%; margin-bottom: 15px; position: relative; overflow: hidden; cursor: pointer; >.gallery-item img < width: 100%; height: auto; vertical-align: top; webkit-filter: grayscale(50%); -moz-filter: grayscale(50%); -o-filter: grayscale(50%); -ms-filter: grayscale(50%); filter: grayscale(50%); -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; >.gallery-item:hover img
  • By using filter: grayscale(50%); , initially, we will make our image 50% gray.
  • In .gallery-item:hover img , it will automatically return to the origional state by making grayscale to 0 filter: grayscale(0%); .
  • We also want to rotate and scale our image when user hover over the image item by using transform: scale(1.2) rotate(-3deg);
Читайте также:  Html color picker rgba

This is not possible for us to add all images manually from a directory. That’s why we will use PHP to get all the images.

  • First store the current directory in a variable using getcwd() .
  • To get the image directory, we need to string concatination here i.e. $working_dir . “/images/”; and store it to $img_dir variable.
  • Now change the current directory location to image directory chdir($img_dir); .
  • To get the all images from a directory, we are going to use PHP glob() function.
  • Using the GLOB_BRACE flag, we can search for files with extensions jpg, gif, png like this glob(«*.», GLOB_BRACE ); and store it into a variable called $files .
  • You can see we have written the extension into the brace “<>” i.e. jpg and JPG. This is because, GLOB_BRACE flag is case sensitive.
  • Again change the directory to root directory chdir($working_dir);.
  • We have changed our curret directory to images directory because if you simply pass glob(«images») , it will return image filename with directory name i.e. “images/1.jpeg”. To get rid of that, we have changed our directory to get only image file name.
  • Now iterate over image files and generate HTML structure dynamically for our gallery.

We have done the main work. Now let’s see how we can make this image gallery look like a responsive masonry grid just like Pinterest.

If you don’t know what a masonry grid is, then you can check our demo. Basically, it does not have a fixed height. This is because we have different sizes of images. It helps to reduce any unnecessary gaps between the images.

 if (timeout) clearTimeout(timeout); else if (execAsap) func.apply(obj, args); timeout = setTimeout(delayed, threshold || 50); >; >; // smartresize jQuery.fn[sr] = function(fn)< return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); >; >)(jQuery,'smartresize'); var colWidth = function () < var w = $container.width(), columnNum = 1, columnWidth = 0; if (w >1200) < columnNum = 3; >else if (w > 900) < columnNum = 3; >else if (w > 600) < columnNum = 3; >else if (w > 400) < columnNum = 2; >else if (w > 300) < columnNum = 1; >columnWidth = Math.floor(w/columnNum); columnWidth = columnWidth - 10; // Item width $container.find('.gallery-item').each(function() < var $item = $(this); var multiplier_w = $item.attr('class').match(/item-w(\d)/); var width = multiplier_w ? columnWidth*multiplier_w[1]-4 : columnWidth-4; // Update item width $item.css(< width: width >); >); return columnWidth; >; var $container = $('.gallery-list'); $container.isotope( < resizable: false, itemSelector: '.gallery-item', percentPosition: true, masonry: < columnWidth: colWidth(), gutter: 10, >>); >); 

Conclusion

You can use any type of image. Make sure you put the same image with lower resolution inside the thumb directory. Depending on your directory structure, you can change the directory names per your requirement. That’s all for today’s tutorial. If you have any questions please comments below.

Читайте также:  Css use classes or ids
About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Hy,
Good tutorial, but when loading images, many of them appear cutted, till refreshing the page.

// init Masonry
var $grid = $(‘.grid’).masonry(// options…
>);
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() $grid.masonry(‘layout’);
>);

So first check the images are loaded or not, then apply masonry.
https://masonry.desandro.com/layout.html

Hello Asish,
I am using the code from this article in a new website and encounter the same problem as mentioned by Roberto.
After reading your comment to him I also loaded the “imagesloaded” script. But I can’t figure out where to put the code that you mention in your comment. I looked at all the codepen’s on the desandro website but nothing works in my situation. Can you be more specific about the code and were to put it?

Please share more details.

Источник

Простая галерея на PHP

Простая галерея на PHP

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

Скрипт простой и его задача, в первую очередь, показать, как можно решать подобные задачи, ведь выводить можно не только картинки, а, например, список файлов в директории. Можно даже сделать свой файловый менеджер. Итак, вот код:

/* Функция для удаления лишних файлов: сюда, помимо удаления текущей и родительской директории, так же можно добавить файлы, не являющиеся картинкой (проверяя расширение) */
function excess($files) $result = array();
for ($i = 0; $i < count($files); $i++) if ($files[$i] != "." && $files[$i] != "..") $result[] = $files[$i];
>
return $result;
>
$dir = «images»; // Путь к директории, в которой лежат изображения
$files = scandir($dir); // Получаем список файлов из этой директории
$files = excess($files); // Удаляем лишние файлы
/* Дальше происходит вывод изображений на страницу сайта (по 4 штуки на одну строку) */
?>

» alt=»»/>

?>
?>

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

Вот так создаётся простая галерея на PHP.

Создано 27.11.2013 12:41:39

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Читайте также:  Модуль sqrt в питоне

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 4 ):

    Лучше не делать никакие 4 штуки на 1 строку, тогда можно сделать адаптивную вёрстку, чтобы в строке было столько картинок, сколько помещается на экране.

    Подскажите, а как сделать чтобы при нажатии на картинку открывалась картинка большого размера?

    Это можно сделать с помощью JavaScript, лучше всего использовать jQuery

    Функция scandir сортирует список, что нежелательно для вывода фоток, т.к при добавлении новых они теряются среди множества других, уже существующих. Флаг SCANDIR_SORT_NONE не работает даже при версии php более 5.4. Чем эту функцию можно заменить?

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Фото Галерея

    Coppermine – это разносторонняя, много функциональная web галерея картинок написанная на языке PHP, с использованием GD или ImageMagick, а так же базу данных MySQL.

    Отличный, простой скрипт фото галереи. Просмотр картинки Full Size в новом, открывающемся окне, авто генерация превью (thumbnail) и многое другое в этом пакете Maian Gallery.

    KoschtIT Image Gallery – это бесплатный и открытый код (open source) PHP скрипта фото галереи. Программа используется для быстрого добавление PHP галереи картинок на уже существующий веб сайт.

    Max’s PHP Photo Album

    Max’s PHP Photo Album – это простой, легкий в использовании PHP скрипт Фото Альбома. Вы можете загружать картинки на ваш сервер, добавлять название/тайтл и описание вашим фото файлам, защитить файлы от просмотра паролем и другие стандартные функции.

    PHPGallery

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

    Simple Gallery – это самая легкая система управления галереи картинок написанная на языке PHP, которая использует jQuery, MySQL и библиотеку GD Library.

    Plogger

    Plogger – это php скрипт галереи картинок принципиально нового поколения с открытым для редактирования кодом. PHP программа не раздута каким-либо лишними функциями или сложной настройкой.

    TinyWebGallery

    Tiny Web Gallery – это бесплатный скрипт Фото Галереи основанный на PHP. Лёгок в установке. Очень удобный, не требует БД (использует xml файл), но не смотря на это, очень много функций, как если бы база данных использовалась.

    Источник

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