0

Код ресайзит(resize) картинки и сохранят в папку. Нужно вызвать функцию ресайза, но как-то красиво, чтоб не дублировать код. Нужно чтоб с размерами 260 * 400 - картинки сохранялись в одну папку, а с размерами 680 * 900 в другую . Как этого добиться?

Вот участок кода, который отвечает за ресайз и содержит путь картинок:

$destPath = $DestImagesDirectory.$file; // путь 
$NewImageWidth = 400;
$NewImageHeight = 260;
$Quality = 90;

Нужно чтоб можно было написать ещё:

$destPath = $DestImagesDirectory.$file;
$NewImageWidth = 680;
$NewImageHeight = 900;
$Quality = 90;

Оборачивал в функцию и вызывал с другими значениями, но не работает ..

Как правильно сделать? Вот весь код :

<?php

//Maximize script execution time
ini_set('max_execution_time', 0);

//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = 'C:\Users\Sun\Desktop\origin-picture-logo/'; //Source Image Directory End with Slash
$DestImagesDirectory = 'D:\260_width_hight/'; //Destination Image Directory End with Slash
$DestImagesDirectory_2 = 'D:\480_440_width_height/';
$NewImageWidth; //New Width of Image
$NewImageHeight; // New Height of Image
$Quality; //Image Quality

//Function that resizes image.
function resizeImage($SrcImage, $DestImage, $MaxWidth = 20, $MaxHeight = 29, $Quality = 90) {
    global $iWidth;
    global $iHeight;
    global $img;

    list($iWidth, $iHeight, $type) = getimagesize($SrcImage);
    $ImageScale = min($MaxWidth / $iWidth, $MaxHeight / $iHeight);
    $NewWidth = ceil($ImageScale * $iWidth);
    $NewHeight = ceil($ImageScale * $iHeight);
    $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);

    switch (strtolower(image_type_to_mime_type($type)))
    {
        case 'image/jpeg':
            $NewImage = imagecreatefromjpeg($SrcImage);
            break;
        case 'image/png':
            $NewImage = imagecreatefrompng($SrcImage);
            break;
        case 'image/gif':
            $NewImage = imagecreatefromgif($SrcImage);
            break;
        default:
            return false;
    }

    // Resize Image
    if (imagecopyresampled($NewCanves, $NewImage, 0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight)) {
        //  echo    $iWidth;
        $stndartwidth = $iWidth;
        // copy file
        if (imagejpeg($NewCanves, $DestImage, $Quality)) {
            imagedestroy($NewCanves);
            return true;
        }
    }
};



//Open Source Image directory, loop through each Image and resize it.

if ($dir = opendir($ImagesDirectory)) {
        while (($file = readdir($dir)) !== false) {

        $imagePath = $ImagesDirectory.$file;
        global $destPath;
        $checkValidImage = @getimagesize($imagePath);

        if (file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
        {
            //Image looks valid, resize.

            $destPath = $DestImagesDirectory.$file;
            $NewImageWidth = 500;
            $NewImageHeight = 260;
            $Quality = 90;

            if (resizeImage($imagePath, $destPath, $NewImageWidth, $NewImageHeight, $Quality)) {
                echo $file.
                ' resize Success!<br />';
            } else {
                echo $file.
                ' resize Failed!<br />';
            }
        }
    }
    //  echo  $imagePath;
    closedir($dir);
}
1
  • А как же оно у вас заработает, если вы используете некие глобальные переменные $iWidth и $iHeght, но при этом нигде не задаете их значения. Судя по всему вам надо вообще избавится от них, ничего глобального использовать не надо
    – Mike
    24 янв 2016 в 21:43

1 ответ 1

1

Для данных целей используйте Imagick:

$bigThumb = new Imagick('myimage.gif');

$bigThumb->resizeImage(680,900,Imagick::FILTER_LANCZOS,1);
$bigThumb->writeImage('mythumb.jpg');

$smallThumb = new Imagick('myimage.gif');

$small->resizeImage(260,400,Imagick::FILTER_LANCZOS,1);
$small->writeImage('mythumb.jpg');

$small->destroy(); 

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.