Галерея изображений в php: приостановить чтение массива файлов, продолжить по клику

0

Мне нужно создать галерею изображений, которая:

  1. отображает эскизы, автоматически созданные из каталога большого изображения, (сделано).
  2. не имеет полос прокрутки по умолчанию для браузера (заменен на Perfect Scrollbar), (сделано).
  3. имеет изображения в столбцах в миниатюрах равной ширины (сделано).
  4. сначала отображает новые изображения в большой директории (сделано).
  5. ленивая загрузка эскизов. (Проблема!)
  6. имеет гладкую прокрутку, как на смартфонах (не достигнуто из-за 5).

Потенциальное бесконечное отображение блоков эскизов (ссылки на другую страницу для больших изображений) или столько, сколько кто-то хочет прокрутить вниз. Галерея будет иметь не менее 1000-2000 эскизов.

Я понимаю, что загрузка так много эскизов сразу может привести к краху браузера, и поэтому я пытался заставить изображения загружать lazilym, но на всю жизнь я не могу использовать какой-либо ленивый плагин для работы на моем сайте. Я попробовал это после удаления идеального scollbar из кода, но все еще не сигары. После долгих поисков я должен прийти к выводу, что ленивая нагрузка "может" не всегда срабатывает.

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

Я создаю код под этим, как и до добавления ленивого плагина изображения.

<head>
    <link href="src/perfect-scrollbar.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="src/jquery.mousewheel.js"></script>
    <script src="src/perfect-scrollbar.js"></script>
    <script>
        jQuery(document).ready(function ($) {
        "use strict";
        $('#Default').perfectScrollbar({ wheelSpeed: 50, wheelPropagation: true, minScrollbarLength: 20 });
        });
    </script>
</head>

<body>
    <style>
    .contentHolder { position:relative; margin:0px auto; padding:0px; width: 100%; height: 100%; overflow: hidden; }
    .contentHolder .content {}
    .spacer { text-align:center }

    html, body {
        margin: 0px;
        padding: 0px;
        background-color:black;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }

    .imagecontainer { width:100%; }

    #videos { width:100%; height:120px; } 

    #photos {
        line-height: 0;
        -webkit-column-count: 5;
        -webkit-column-gap:0px;
        -moz-column-count: 5;
        -moz-column-gap:0px;
        column-count:5;
        column-gap:0px;
        float:left;
    }

    #photos img {
        /* Just in case there are inline attributes */
        width: 99% !important;
        height: auto !important;
        opacity:0.8;
        filter:alpha(opacity=80);
        -webkit-transition: all 500ms ease;
        -moz-transition: all 500ms ease;
        -o-transition: all 500ms ease;
        -ms-transition: all 500ms ease;
        transition: all 500ms ease;
        -webkit-backface-visibility: hidden;
    }

    #photos img:hover { 
        width: 100% !important;
        opacity:1;
        filter:alpha(opacity=100); /* For IE8 and earlier */
    }
    </style>

<div style="position:fixed; z-index:4; width:100%; background-color:rgba(100,100,100,0.5)">Simple Menu Bar-Currently empty.</div>
<div id="Default" class="contentHolder">
    <div class="content">
    <section id="photos">

    <?php

    /* Get Directory with Dates Last Modified */

    function getimageswithdates(){
    $directory="preload-images/"; 
    $sortOrder="newestFirst"; 

    $results = array(); 
    $handler = opendir($directory); 

    while ($file = readdir($handler)) {
        if ($file != '.' && $file != '..' && $file != "robots.txt" && $file != ".htaccess"){ 
            $currentModified = filectime($directory."/".$file); 
            $file_names[] = $file; 
            $file_dates[] = $currentModified; 
        } 
    } 

    closedir($handler); 

    //Sort the date array by preferred order 
    if ($sortOrder == "newestFirst"){ 
        arsort($file_dates); 
    } else { 
        asort($file_dates); 
    } 

    //Match file_names array to file_dates array 
    $file_names_Array = array_keys($file_dates); 
    foreach ($file_names_Array as $idx => $name) $name=$file_names[$name]; 
    $file_dates = array_merge($file_dates); 

    //Loop through dates array, save list to array and echo the list 
    $filelist = array();
    $i = 0;
    foreach ($file_dates as $file_dates){ 
        $date = $file_dates; 
        $j = $file_names_Array[$i]; 
        $file = $file_names[$j]; 
        $i++; 
        $filelist[] = $file;
        echo '<a href="color.php?see='.str_ireplace(".jpg", " ", "$file"). '" class="photo-link smoothbox" rel="gallery">
        <img src="preload-images-thumbs/'.$file.'"  /></a>'; 
        }
    echo '</section> </div>';
    }

    /** settings **/
    $images_dir = 'preload-images/';
    $thumbs_dir = 'preload-images-thumbs/';
    $thumbs_width = 200;

    /* function:  generates thumbnail */
    function make_thumb($src,$dest,$desired_width) {
    /* read the source image */
    $source_image = imagecreatefromjpeg($src);
    $width = imagesx($source_image);
    $height = imagesy($source_image);
    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height*($desired_width/$width));
    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width,$desired_height);
    /* copy source image at a resized size */
    imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
    /* create the physical thumbnail image to its destination */
    imagejpeg($virtual_image,$dest);
    }

    /** generate photo gallery **/
    $image_files = get_files($images_dir);
    if(count($image_files)) {
        $index = 0;
        foreach($image_files as $index=>$file) {
            $index++;
            $thumbnail_image = $thumbs_dir.$file;
            if(!file_exists($thumbnail_image)) {
                $extension = get_file_extension($thumbnail_image);
                if($extension) { make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width); } 
            } 
        }
    }
    else { }

    /* function:  returns files from dir */
    function get_files($images_dir,$exts = array('jpg')) {
        $files = array();
        if($handle = opendir($images_dir)) {
            while(false !== ($file = readdir($handle))) {
                $extension = strtolower(get_file_extension($file));
                if($extension && in_array($extension,$exts)) {
                    $files[] = $file; }
            }
        closedir($handle);
        }
        return $files;
    }

    /* function:  returns a file extension */
    function get_file_extension($file_name) {
    return substr(strrchr($file_name,'.'),1);
    }

    echo getimageswithdates();

    ?>

</body>
</html>

--------------------- РЕДАКТИРОВАТЬ -------------------

Цикл foreach

$filelist = array();
$i = 0;
foreach ($file_dates as $file_dates){ 
    $date = $file_dates; 
    $j = $file_names_Array[$i]; 
    $file = $file_names[$j]; 
    $i++; 
    $filelist[] = $file;
    echo '<a href="color.php?see='.str_ireplace(".jpg", " ", "$file"). '" class="photo-link smoothbox" rel="gallery">
    <img src="preload-images-thumbs/'.$file.'"  /></a>'; 
    }

Может ли цикл приостановиться, если я == 30, затем возобновить нажатие и цикл в 30 секунд?

  • 0
    Это много кода, чтобы пройти через. Можете ли вы свести его к 10 или 20 строкам, которые нужно изменить?
  • 1
    Готово. Пожалуйста, прокрутите вниз до «Редактировать»
Теги:
lazy-loading
auto-generate

1 ответ

0

Ваш подход неправильный, для XHR (ajax), чтобы достичь этого, отправьте соответствующие параметры из javascript в php, чтобы он зависал в определенном диапазоне, который вы хотите.

  • 0
    Читая об этом. Спасибо :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню