Page 19 of 37

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:11 am
by simonmlewis
I'm looking at this bit:

Code: Select all

case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
Thinking I can add this sort of thing to the $images_path section above.

Code: Select all

case 'stockbanners':
           $images_path = '/images/stockbanners';
            break;
And some sort of else if ... and tell it to do all others to /images/pages.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:21 am
by Celauran
simonmlewis wrote:I'm looking at this bit:

Code: Select all

case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
That works. Notice how it's the same as categories and products? You can simply add [inline]case 'stockbanners':[/inline] below [inline]case 'products':[/inline] to have the three options return the same thing.

Code: Select all

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}
simonmlewis wrote:Thinking I can add this sort of thing to the $images_path section above.

Code: Select all

case 'stockbanners':
           $images_path = '/images/stockbanners';
            break;
And some sort of else if ... and tell it to do all others to /images/pages.
That's an option. See if you can't flesh it out a bit more.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:27 am
by simonmlewis
How about this?
Note the $actualfolder variable.

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
      case 'stockbanners':
    $actualfolder = 'stockbanners';
    break;
     default:
     $actualfolder = 'pages';
     break;
     
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $images_path = '/images/$actualfolder'; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
    case 'stockbanners':
    $actualfolder = 'stockbanners';
    break;
     default:
     $actualfolder = 'pages';
     break;
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:28 am
by Celauran
case needs to be inside a switch statement, and the switch statement needs an argument. You're on the right track, though. Keep going.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:30 am
by Celauran
Also, variables are not interpolated inside single quotes, so you'll need to use double quotes when defining $images_path.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:31 am
by simonmlewis
Better?

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder => stockbanners;
      break;
      default:
      $actualfolder => pages;
      break;
     }
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $images_path = '/images/$actualfolder'; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder => stockbanners;
      break;
      default:
      $actualfolder => pages;
      break;
     }
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:37 am
by Celauran
Getting there. Where is $resize_option coming from? Your second argument is called $resize_type. Also, you want to be assigning values to the $actualfolder variable. That => is going to cause syntax errors. Finally, stockbanners and pages are strings and so need to be wrapped in quotes.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:42 am
by simonmlewis

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $images_path = '/images/$actualfolder'; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:47 am
by Celauran
Better. There's still the question of where $resize_option is coming from, and you still need to fix the quotes on $image_path line. Are you trying this as you go? Are you getting meaningful errors back?

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:50 am
by simonmlewis
I'm not testing it, I'm finding the errors after your guidance, and seeing where I am wrong.
I don't know where that $resize_option comes from. I see it in your resize code. Would it be better to move that to the top of the page?

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $images_path = '/images/{$actualfolder}'; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
  switch($resize_option) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 10:58 am
by Celauran
simonmlewis wrote:I'm not testing it, I'm finding the errors after your guidance, and seeing where I am wrong.
I don't know where that $resize_option comes from. I see it in your resize code. Would it be better to move that to the top of the page?
This is a question of scope. Functions only have access to variables that are declared within them or passed in as parameters. You are accepting two parameters: $filename and $resize_type. I've been trying to hint that you should be using $resize_type as that's what it's called within the scope of this function.

Give this a read to better understand scope: http://php.net/manual/en/language.variables.scope.php
I also recommend this free series of video tutorials on some of the basics of PHP to help clear up any grey areas: https://laracasts.com/series/php-for-beginners
simonmlewis wrote:

Code: Select all

<?php
...
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . "{$actualfolder}";
    $images_path = '/images/{$actualfolder}'; // Still need this for srcset output
...
It's the $images_path line you need to worry about. Variables aren't interpolated inside single quotes. Should look like this:

Code: Select all

<?php
...
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $images_path = "/images/{$actualfolder}"; // Still need this for srcset output
...

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 11:02 am
by simonmlewis
I used resize_option as that is what was in that other function.

Is this correct?

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $images_path = "/images/{$actualfolder}"; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>
Also I got a bit confused between needing to put a variable inside braces, and where it is on it's only after a dot.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 11:03 am
by Celauran
This looks good. Is it working as expected? If not, what error(s) are you encountering?

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 11:07 am
by simonmlewis
Getting into a bit of a mucky fuddle here again!
Code as it is now:

Code: Select all

<?php
require_once '/vendor/autoload.php';

// Returns required quality settings for Imagine based on image's extension
function getImageOptions($extension)
{
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $options = ['jpeg_quality' => 97];
            break;
        case 'png':
            $options = ['png_compression_level' => 8];
            break;
        default:
            $options = [];
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    $root_directory = dirname(__DIR__);
    $images_directory = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $images_path = "/images/{$actualfolder}"; // Still need this for srcset output
    $source_directory = $root_directory . $images_directory;
    $srcset = [];

    $widths = getWidths($resize_type);

    if (file_exists($source_directory . DIRECTORY_SEPARATOR . $filename)) {
        $basename = pathinfo($filename, PATHINFO_FILENAME);
        $extension = pathinfo($filename, PATHINFO_EXTENSION);

        foreach ($widths as $size => $width) {
            $fullname = $basename . '_' . $size . '.' . $extension;
            if (file_exists($source_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width);
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            }
        }
    }

    return implode(', ', $srcset);
}

// Returns an array of widths, keyed by target screen size
function getWidths($resize_option)
{
    switch($resize_option) {
        case 'categories':
        case 'products':
        case 'stockbanners':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            ];
            break;
        case 'wide':
            $widths = [
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            ];
            break;
        case 'desktopslide':
            $widths = [
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            ];
            break;
        default:
            $widths = [];
            break;
    }

    return $widths;
}

// Takes input from a form post and saves original image plus all required resizes
function resizeImage($path_to_file, $file_name, $resize_type)
{
    $imagine = new Imagine\Gd\Imagine();
    
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($file_name);
    $prefix = time();

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($path_to_file);

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $target_directory . DIRECTORY_SEPARATOR . "{$prefix}{$pathinfo['basename']}";
    $image->save($path_to_original, $options);

    // Resize

    // Get the size of the original image
    $box = $image->getSize();

    // Get the sizes we need
    $widths = getWidths($resize_type);

    // Create resized images
    foreach ($widths as $key => $width) {
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        $new_filename = "{$prefix}{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";

        // Re-open the original for scaling so we're not creating a larger image from a smaller
        $source = $imagine->open($path_to_original);
        $source->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
}

// Resizes a single image to a specific size and with a specific suffix
function resizeSingleImage($original, $suffix, $width)
{
    $imagine = new Imagine\Gd\Imagine();
  // Get the sizes we need
    $widths = getWidths($resize_type);
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      default:
      $actualfolder = 'pages';
      break;
     }
    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $actualfolder;
    $pathinfo = pathinfo($original);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($target_directory . DIRECTORY_SEPARATOR . $original);

    // Get the size of the original image
    $box = $image->getSize();

    $ratio = $width / $box->getWidth();
    $scaled_box = $box->scale($ratio);
    $new_filename = "{$pathinfo['filename']}_{$suffix}.{$pathinfo['extension']}";

    $options = getImageOptions($pathinfo['extension']);
    $image->resize($scaled_box)->save($target_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
}

?>
A *few* errors:
[text]Notice: Undefined variable: resize_type in C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php on line 144

Notice: Undefined variable: resize_type in C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php on line 146

Fatal error: Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File C:\xampp\phpMyAdmin\site-wide\images\pages\ does not exist.' in C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php:72 Stack trace: #0 C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Gd\Imagine.php(86): Imagine\Image\AbstractImagine->checkPath('C:\\xampp\\phpMyA...') #1 C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php(157): Imagine\Gd\Imagine->open('C:\\xampp\\phpMyA...') #2 C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php(49): resizeSingleImage(NULL, 475, 237) #3 C:\xampp\phpMyAdmin\site-wide\includes\page.inc(310): getSrcSet(NULL, 'stockbanners') #4 C:\xampp\phpMyAdmin\site-wide\index.php(42): include('C:\\xampp\\phpMyA...') #5 C:\xampp\phpMyAdmin\site-wide\index.php(437): getPage(Object(PDO)) #6 {main} thrown in C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php on line 72[/text]
I think it's down to my resize_type being very wrong somewhere.

Re: Image Resizing Script required - a better one...

Posted: Thu Mar 09, 2017 11:18 am
by Celauran
So let's look at lines 144 and 146. Looks like you've copy/pasted some code into the resizeSingleImage function. Two things here. First, if you find yourself copying and pasting bits of code around, that's generally a good indicator that you should extract a function. Second, you are again referencing a variable that does not exist within the scope of the function. You have already determined what $actualfolder is, why not add a fourth parameter to resizeSingleImage and pass that value in?