Skip to content

Instantly share code, notes, and snippets.

@Zlatov
Last active January 26, 2016 13:25
Show Gist options
  • Select an option

  • Save Zlatov/d4968960e10d3405658c to your computer and use it in GitHub Desktop.

Select an option

Save Zlatov/d4968960e10d3405658c to your computer and use it in GitHub Desktop.

Revisions

  1. Zlatov revised this gist Jan 26, 2016. No changes.
  2. Zlatov revised this gist Jan 26, 2016. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions resize-img.php
    18 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
  3. Zlatov revised this gist Jan 26, 2016. No changes.
  4. Zlatov revised this gist Jan 16, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions resize-img.php
    Original file line number Diff line number Diff line change
    @@ -23,8 +23,8 @@
    // contain - содержит все изображение в заданных рамках
    // cover - заполняет указанные рамки обрезая лишнее
    $resizeThumbnailType = 'cover';
    $thumbnailWidth = 200;
    $thumbnailHeight = 200;
    $thumbnailWidth = 250;
    $thumbnailHeight = 250;

    $lightbox = '';

  5. Zlatov revised this gist Jan 16, 2016. No changes.
  6. Zlatov revised this gist Jan 10, 2016. No changes.
  7. Zlatov revised this gist Jan 9, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion resize-img.php
    Original file line number Diff line number Diff line change
    @@ -71,7 +71,7 @@
    $r2 = str_replace('\\','/',$r2);
    $r2 = substr($r2,strlen($_SERVER['DOCUMENT_ROOT']));
    }
    $lightbox .= "<a href=\"".$r2."\" data-lightbox=\"lightbox\"><img src=\"".$r1."\"></a>\n";
    $lightbox .= "<a href=\"".$r1."\" data-lightbox=\"lightbox\"><img src=\"".$r2."\"></a>\n";
    }
    }
    closedir($dir);
  8. Zlatov created this gist Jan 9, 2016.
    196 changes: 196 additions & 0 deletions resize-img.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,196 @@
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>




    <?php
    $toResizeImg = true;
    $resizeImg = true;

    // contain - содержит все изображение в заданных рамках
    // cover - заполняет указанные рамки обрезая лишнее
    $resizeType = 'contain';
    $imgWidth = 1280;
    $imgHeight = 720;
    $createThumbnail = true;

    // contain - содержит все изображение в заданных рамках
    // cover - заполняет указанные рамки обрезая лишнее
    $resizeThumbnailType = 'cover';
    $thumbnailWidth = 200;
    $thumbnailHeight = 200;

    $lightbox = '';

    $getcwd = getcwd();
    $path = $getcwd;
    $dir = opendir($path);
    chdir($path);
    while ($f = readdir($dir)) {
    if (is_file($f) && ($f !== ".") && ($f !== "..")) {
    $r1 = $r2 = $path . DIRECTORY_SEPARATOR . $f;
    if ($resizeImg) {
    echo 'Преобразуемое изображение: ' . $path . DIRECTORY_SEPARATOR . $f;
    echo '<br>';
    $return = transformImg($path . DIRECTORY_SEPARATOR . $f, $imgWidth, $imgHeight, $resizeType, false, true);
    if (!is_array($return)) {
    echo 'Ошибка! ' . $return;
    echo '<br>';
    }
    else {
    $r1 = $return[0];
    echo 'Success transform.';
    echo '<br>';
    }
    echo '<br>';
    }
    if ($createThumbnail) {
    echo 'Изображение для миниатюры: ' . $path . DIRECTORY_SEPARATOR . $f;
    echo '<br>';
    $return = transformImg($path . DIRECTORY_SEPARATOR . $f, $thumbnailWidth, $thumbnailHeight, $resizeThumbnailType, true, true);
    if (!is_array($return)) {
    echo 'Ошибка! ' . $return;
    echo '<br>';
    }
    else {
    $r2 = $return[0];
    echo 'Успешное создание миниатюры.';
    echo '<br>';
    }
    echo '<br>';
    }
    if (DIRECTORY_SEPARATOR=='\\') {
    $r1 = str_replace('\\','/',$r1);
    $r1 = substr($r1,strlen($_SERVER['DOCUMENT_ROOT']));
    $r2 = str_replace('\\','/',$r2);
    $r2 = substr($r2,strlen($_SERVER['DOCUMENT_ROOT']));
    }
    $lightbox .= "&lt;a href=\"".$r2."\" data-lightbox=\"lightbox\">&lt;img src=\"".$r1."\">&lt;/a>\n";
    }
    }
    closedir($dir);

    echo '<pre>';
    echo $lightbox;
    echo '</pre>';

    function transformImg($pathToFile, $destination_width, $destination_height, $resizeType = 'cover', $createThumbnailname = false, $toResizeImg = true) {
    $pathinfo = pathinfo($pathToFile);
    $valid_types = array("jpg", "jpeg", "png");
    if (!in_array($pathinfo['extension'], $valid_types)) return sprintf("Неподходящее разрешение файла %s", $pathinfo['filename'] . '.' . $pathinfo['extension']);
    if (filesize($pathToFile) > 9 * 1024 * 1024) return sprintf("Слишком большой размер файла %s", $pathinfo['filename'] . '.' . $pathinfo['extension']);
    if (!list($source_width, $source_height) = getimagesize($pathToFile)) return sprintf("Не получилось определить размеры изображения %s", $pathinfo['filename'] . '.' . $pathinfo['extension']);

    // Источник
    switch ($pathinfo['extension']) {
    case 'jpeg':
    $source = imagecreatefromjpeg($pathToFile);
    break;

    case 'jpg':
    $source = imagecreatefromjpeg($pathToFile);
    break;

    case 'gif':
    $source = imagecreatefromgif($pathToFile);
    break;

    case 'png':
    $source = imagecreatefrompng($pathToFile);
    break;

    case 'bmp':
    $source = imagecreatefromwbmp($pathToFile);
    break;
    }

    // Соотношения
    $destination_ratio = $destination_width / $destination_height;
    $source_ratio = $source_width / $source_height;

    // Область копирования
    $frame_width = $source_width;
    $frame_height = $source_height;
    $frame_x = $frame_y = 0;

    switch ($resizeType) {
    case 'cover':

    // Расчёт области копирования
    if ($source_ratio > $destination_ratio) {
    $frame_width = floor($destination_width * $source_height / $destination_height);
    $frame_x = floor($source_width / 2 - $frame_width / 2);
    }
    else {
    $frame_height = floor($destination_height * $source_width / $destination_width);
    $frame_y = floor($source_height / 2 - $frame_height / 2);
    }
    break;

    case 'contain':

    // Расчёт назначения
    if ($source_ratio > $destination_ratio) {
    $destination_height = floor($source_height * $destination_width / $source_width);
    }
    else {
    $destination_width = floor($source_width * $destination_height / $source_height);
    }
    break;
    }

    $destination = imagecreatetruecolor($destination_width, $destination_height);

    // Создаём назначение
    imagefill($destination, 0, 0, imagecolorallocate($destination, 255, 255, 255));

    // Закрашиваем назначение белым
    imagecopyresampled($destination, $source, 0, 0, $frame_x, $frame_y, $destination_width, $destination_height, $frame_width, $frame_height);

    // Копируем с ресайзом
    $name = translit($pathinfo['filename']);
    if ($createThumbnailname) {
    $name = $name . '-thumbnail';
    }
    if ($toResizeImg) {
    $to = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . 'resize-img';
    if (!is_dir($to)) if (!mkdir($to)) return sprintf('Не удалось создать директорию %s', $to);
    $to = $to . DIRECTORY_SEPARATOR . $name . '.jpg';
    }
    else {
    $to = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . $name . '.jpg';
    }
    if (!imagejpeg($destination, $to, 100)) return sprintf("Что-то не так при сохранении");
    imagedestroy($destination);
    imagedestroy($source);
    $return = array($to);

    return $return;
    }

    // Транслитерация ГОСТ 7.79-2000 (Б) с отступлениями
    function translit($text) {
    if (DIRECTORY_SEPARATOR == '\\') {
    $text = iconv('windows-1251', 'UTF-8', $text);
    }
    $text = mb_strtolower($text, 'UTF-8');
    $replace = array("а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ё" => "e", "ж" => "j", "з" => "z", "и" => "i", "й" => "y", "к" => "k", "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p", "р" => "r", "с" => "s", "т" => "t", "у" => "u", "ф" => "f", "х" => "h", "ц" => "c", "ч" => "ch", "ш" => "sh", "щ" => "sch", "ъ" => "", "ы" => "y", "ь" => "", "э" => "e", "ю" => "yu", "я" => "ya", " " => "-");
    $text = strtr($text, $replace);
    $text = preg_replace('/[^a-z0-9_-]/', '', $text);
    $text = preg_replace('/[-]{2,}/', '-', $text);
    $text = preg_replace('/[_]{2,}/', '_', $text);
    $text = trim($text, '-_');
    return $text;
    }
    ?>



    </body>
    </html>