Page 29 of 37

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

Posted: Tue Mar 14, 2017 6:02 am
by simonmlewis
Another little side note. At the moment we have one image for the primary photo in /images/productphotos/small.
This script will create four new ones for each primary image. My concern is that there will be forever-more, that small file that doesn't have the _ext on it.
It's not vital, but it would be good if on-the-fly, the resize script could delete anything in /small that is the same filename as in /image/productphotos for that file.

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

Posted: Tue Mar 14, 2017 6:18 am
by simonmlewis
Now trying the resize on the fly on our live server, but got an error:

Code: Select all

mod_fcgid: stderr: PHP Parse error: syntax error, unexpected '[' in /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/functions/functionConsumerResize.php on line 26, referer: http://sand.site.co.uk/categ/support-tops
I think it is because we have [ where we need (. But even if I do that with array(, it still fails.

When I tried it, it also didn't like $srcset = []; I Tryed $srcset = array();, but it didn't like that either.

UPDATE...

In the error now it is looking in /images/pages.

[text]mod_fcgid: stderr: PHP Fatal error: Uncaught exception 'Imagine\\Exception\\InvalidArgumentException' with message 'File /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/images/pages/17935160g1.jpg does not exist.' in /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/vendor/imagine/imagine/lib/Imagine/Image/AbstractImagine.php:72, referer: http://sand.site.co.uk/categ/support-tops[/text]

Not sure why.........

This is the code on the include file:

Code: Select all

        $image = $row->photoprimary;
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$row->title'>";

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

Posted: Tue Mar 14, 2017 6:39 am
by simonmlewis
My goodness I am seeing some errors now.

Here's one:
[text]mod_fcgid: stderr: #1 /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/functions/functionConsumerResize.php(176): Imagine\\Gd\\Imagine->open('/var/www/vhosts...'), referer: http://sand.site.co.uk/shirts[/text]

This is the function file as of now. something is definitely messing up here.

Code: Select all

<?php
require_once (dirname(__DIR__). '/vendor/autoload.php');

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

    return $options;
}


function getPaths($resize_type)
{
// default for all paths,.
    $paths = array(
        'fullsize' => DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'pages',
        'thumbnail' => DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'pages',
    );
// set for product photo uploads
    if ($resize_type === 'thumbnails') {
        $paths['fullsize'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'productphotos';
        $paths['thumbnail'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'productphotos' . DIRECTORY_SEPARATOR . 'small';
    }
// set for stock banner uploads
    if ($resize_type === 'stockbanners') {
        $paths['fullsize'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'stockbanners';
        $paths['thumbnail'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'stockbanners';
    }

    return $paths;
}


function getSrcSet($filename, $resize_type = 'wide')
{
    $root_directory = dirname(__DIR__);

    $paths = getPaths($resize_type);
    // sets the source path for the big images
    $fullsize_directory = $root_directory . $paths['fullsize'];
    // sets the source path for the thumbnail images (prod photos)
    $thumbnail_directory = $root_directory . $paths['thumbnail'];

    $images_path = str_replace(DIRECTORY_SEPARATOR, '/', $paths['thumbnail']);
    $srcset = array();

    $widths = getWidths($resize_type);

    if (file_exists($fullsize_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($thumbnail_directory . DIRECTORY_SEPARATOR . $fullname)) {
                $srcset[] = "{$images_path}/{$fullname} {$size}w";
            } else {
                resizeSingleImage($filename, $size, $width, $resize_type);
                $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 = array(
                '475' => 237,
                '768' => 384,
                '1920' => 451,
            );
            break;
        case 'wide':
            $widths = array(
                '475' => 237,
                '768' => 384,
                '1920' => 950,
            );
            break;
        case 'desktopslide':
            $widths = array(
                '475' => 475,
                '768' => 768,
                '1920' => 1920,
            );
            break;
        case 'thumbnails':
            $widths = array(
                '475' => 237,
                '768' => 384,
                '1920' => 451,
                '2520' => 600,
            );
            break;            
        default:
            $widths = array();
            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();
    $paths = getPaths($resize_type);
    $fullsize_directory = dirname(__DIR__) . $paths['fullsize'];
    $thumbnail_directory = dirname(__DIR__) . $paths['thumbnail'];
    $pathinfo = pathinfo($file_name);
    $prefix = time();
    $renamed = "{$prefix}_{$pathinfo['basename']}";

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

    // Save the original
    $options = getImageOptions($pathinfo['extension']);
    $path_to_original = $fullsize_directory . DIRECTORY_SEPARATOR . $renamed;
    $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($thumbnail_directory . DIRECTORY_SEPARATOR . $new_filename, $options);
    }
    return $renamed;
}

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

    $paths = getPaths($type);
    // get the source file ready for renaming
    $source_directory = dirname(__DIR__) . $paths['fullsize'];
    // where is the file going to be saved?
    $target_directory = dirname(__DIR__) . $paths['thumbnail'];
    $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: Tue Mar 14, 2017 7:11 am
by Celauran
Looks like there are a few things going on, then. You definitely need to use array(...) rather than [...] since it's PHP 5.3. Your require statements should probably use absolute paths, using a combination of dirname() and __DIR__ before the file name. That's a fair bit to catch up on this morning and it appears you have already resolved a number of issues yourself, so try making the changes mentioned above and let me know where things are at.

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

Posted: Tue Mar 14, 2017 7:18 am
by Celauran
simonmlewis wrote:In the error now it is looking in /images/pages.

[text]mod_fcgid: stderr: PHP Fatal error: Uncaught exception 'Imagine\\Exception\\InvalidArgumentException' with message 'File /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/images/pages/17935160g1.jpg does not exist.' in /var/www/vhosts/site.co.uk/subdomains/sand.site.co.uk/httpdocs/vendor/imagine/imagine/lib/Imagine/Image/AbstractImagine.php:72, referer: http://sand.site.co.uk/categ/support-tops[/text]

Not sure why.........
Pretty standard file not found error. Check that the path is correct, check that the bit after /images/ matches the structure of the image type you're using (ie. that it should be pages and not, say, stockbanners). If that's fine, check that the image itself exists, remembering that Linux file systems are case sensitive. With some older iterations of this script saving to the database before moving the file, it's possible that an entry exists in the database but its corresponding image doesn't actually exist. In any event it's worth making sure that you call file_exists before trying to open an image with Imagine. Alternately, ensure you have a try/catch block in place for when these exceptions are thrown.

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

Posted: Tue Mar 14, 2017 7:25 am
by simonmlewis
This is all correct. The default is images/pages, but thumbnails is product photos and small.
It seems that since we added this additional folder structure element, things have gone a little haywire.

But I don't see a fault in it.

Code: Select all

function getPaths($resize_type)
{
// default for all paths,.
    $paths = array(
        'fullsize' => DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'pages',
        'thumbnail' => DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'pages',
    );
// set for product photo uploads
    if ($resize_type === 'thumbnails') {
        $paths['fullsize'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'productphotos';
        $paths['thumbnail'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'productphotos' . DIRECTORY_SEPARATOR . 'small';
    }
// set for stock banner uploads
    if ($resize_type === 'stockbanners') {
        $paths['fullsize'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'stockbanners';
        $paths['thumbnail'] = DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'stockbanners';
    }

    return $paths;
}

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

Posted: Tue Mar 14, 2017 7:27 am
by simonmlewis
ps it's not thru missing images, because this is happening on all category pages on the demo server. It gets to the first image and crashes on screen with no errors. It's all in the logs.

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

Posted: Tue Mar 14, 2017 7:28 am
by Celauran
That function looks fine to me. Try calling the function by itself (even in a separate test script if you like) and see what you get back. The problem may lie elsewhere.

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

Posted: Tue Mar 14, 2017 7:29 am
by Celauran
simonmlewis wrote:ps it's not thru missing images, because this is happening on all category pages on the demo server. It gets to the first image and crashes on screen with no errors. It's all in the logs.
Interesting. Works fine locally, though? Are you able to upload new images on the demo server? What are the error messages you're seeing? Trying to ascertain what all is going wrong and where.

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

Posted: Tue Mar 14, 2017 7:32 am
by simonmlewis
LOTS of info here... hopefully it helps.

I'm not getting errors on my local version, which I suppose is good as we have somewhere to go:

[text]
<b>Notice</b>: Undefined variable: resize_type in <b>C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php</b> on line <b>168</b><br />
<br />
<b>Fatal error</b>: Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File C:\xampp\phpMyAdmin\site-wide\images\pages\11402787hg116-hfc-1.jpg 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(176): Imagine\Gd\Imagine->open('C:\\xampp\\phpMyA...')
#2 C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php(69): resizeSingleImage('11402787hg116-h...', 475, 237, 'thumbnails')
#3 C:\xampp\phpMyAdmin\site-wide\includes\categ.inc(843): getSrcSet('11402787hg116-h...', 'thumbnails')
#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}
t in <b>C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php</b> on line <b>72</b><br />[/text]

the Categ.inc file has this:

Code: Select all

require_once (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'functionConsumerResize.php');
Maybe I can't use this on my local version??

Also:

Code: Select all

<b>Fatal error</b>:  Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File C:\xampp\phpMyAdmin\site-wide\images\pages\11402787hg116-hfc-1.jpg does not exist.' in C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php:72
Why is it looking in \images\pages ???
This is on a category (thumbnails) page.

Code: Select all

$image = $rowprod->photoprimary;        
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$rowprod->title'>";
And a little further down, as the fiurst set is for featured promos...

Code: Select all

    if (isset($row->bundleroman1) && $row->bundleroman1 != '')
{
if (isset($row->photoprimary) && $row->photoprimary != '')
{
        $image = $row->photoprimary;
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$row->title'>";
}
else
{
echo "<img src='/images/blank_bundle.jpg'   alt='no image available' />";
}
}
else
{
if ($row->photoprimary == "" || $row->photoprimary == NULL)
        {
        echo "<img src='/images/blank.jpg'>";
        }
        else
        {
        $image = $row->photoprimary;
$srcset = getSrcSet($image, 'thumbnails');
echo "<img src='/images/productphotos/$image' srcset='{$srcset}' alt='$row->title'>";
        }
        }

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

Posted: Tue Mar 14, 2017 7:40 am
by Celauran
simonmlewis wrote:I'm not getting errors on my local version, which I suppose is good as we have somewhere to go:

[text]
<b>Notice</b>: Undefined variable: resize_type in <b>C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php</b> on line <b>168</b><br />
<br />
<b>Fatal error</b>: Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File C:\xampp\phpMyAdmin\site-wide\images\pages\11402787hg116-hfc-1.jpg 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(176): Imagine\Gd\Imagine->open('C:\\xampp\\phpMyA...')
#2 C:\xampp\phpMyAdmin\site-wide\functions\functionConsumerResize.php(69): resizeSingleImage('11402787hg116-h...', 475, 237, 'thumbnails')
#3 C:\xampp\phpMyAdmin\site-wide\includes\categ.inc(843): getSrcSet('11402787hg116-h...', 'thumbnails')
#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}
t in <b>C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php</b> on line <b>72</b><br />[/text]
This does look to be on your local, given the C:\. The undefined variable is probably a good place to start. Let's take a look at functionConsumerResize.php and see what's what.
simonmlewis wrote:the Categ.inc file has this:

Code: Select all

require_once (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'functions' . DIRECTORY_SEPARATOR . 'functionConsumerResize.php');
Maybe I can't use this on my local version??
I would expect relative file locations to be the same, so I see no reason it shouldn't work on both. Is require_once throwing an error here?
simonmlewis wrote:Also:

Code: Select all

<b>Fatal error</b>:  Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File C:\xampp\phpMyAdmin\site-wide\images\pages\11402787hg116-hfc-1.jpg does not exist.' in C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php:72
Why is it looking in \images\pages ???
This is on a category (thumbnails) page.
Seems to suggest getPaths is not working correctly as it's returning pages instead of productphotos. Let's check that also.

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

Posted: Tue Mar 14, 2017 7:45 am
by simonmlewis
Ok. How do I check that it's pulling it through?
Also, I see: $imagine = new Imagine\Gd\Imagine(); is in resizeImage, but not in getSrcSet.

Does it need to be there?
Should the top of the functions file be:

require_once (dirname(__DIR__). '/vendor/autoload.php');
$imagine = new Imagine\Gd\Imagine();

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

Posted: Tue Mar 14, 2017 7:50 am
by Celauran
simonmlewis wrote:Ok. How do I check that it's pulling it through?
The nice thing about having things split out into functions is that you can test them in isolation. One day we can get to unit testing, but for now you can create a test.php file, define the variables you need, call the function you want, and dump the results.
simonmlewis wrote:Also, I see: $imagine = new Imagine\Gd\Imagine(); is in resizeImage, but not in getSrcSet.
Strictly speaking, getSrcSet doesn't resize anything, so it doesn't need imagine. The on-the-fly resizing is delegated to resizeSingleImage which, as you can see, does instantiate Imagine.
simonmlewis wrote:Should the top of the functions file be:

require_once (dirname(__DIR__). '/vendor/autoload.php');
$imagine = new Imagine\Gd\Imagine();
Not for now. If we were to make a class out of this functions file, then maybe having Imagine as a class property would make sense, but we're not there yet.

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

Posted: Tue Mar 14, 2017 7:55 am
by simonmlewis

Code: Select all

<?php

require_once (dirname(__DIR__) . DIRECTORY_SEPARATOR  . 'functions' . DIRECTORY_SEPARATOR . 'functionConsumerResize.php');

$imagine = new Imagine\Gd\Imagine();
var_dump($imagine);
?>
Result:
[text]
Warning: require_once(C:\xampp\phpMyAdmin\functions\functionConsumerResize.php): failed to open stream: No such file or directory in C:\xampp\phpMyAdmin\site-wide\composer-test.php on line 3

Fatal error: require_once(): Failed opening required 'C:\xampp\phpMyAdmin\functions\functionConsumerResize.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\phpMyAdmin\site-wide\composer-test.php on line 3[/text]
I think it is going back too far.

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

Posted: Tue Mar 14, 2017 7:57 am
by Celauran
Looks that way. Remember that __DIR__ is the directory of the current file and each dirname() goes up one directory.