Page 22 of 37

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

Posted: Mon Mar 13, 2017 7:55 am
by Celauran
simonmlewis wrote:I understand. It's basically throw a fit because the image I want to delete, is not there.
It shouldn't. If glob doesn't find anything, it returns an empty array. That error message you posted earlier complained that it was expecting but not receiving an array, which leads me to believe glob is returning false, suggesting there's an error with the glob pattern. I'd start there.
simonmlewis wrote:But I have a feeling, a nagging feeling it's finding the files, but the files cannot locate the composer "engine" installed on the server.
Composer is a package manager. Aside from providing the autoloader, which would fail if missing since it's require_once, it shouldn't matter if it's on the server or not. Is this a production server? I can understand errors not being displayed, but they should be logged somewhere. You need to be able to debug this.

It looks like there are a few things going wrong here. Let's try to focus on one at a time. Glob is already giving you error messages, so I'd try to resolve that first. From there, we can look at the issues with uploading new images.

Have you confirmed that the autoloader is being required and not throwing errors? Are you able to manually create a new instance of Imagine? Those would rule out Composer being an issue here, and would therefore be one fewer thing to worry about.

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

Posted: Mon Mar 13, 2017 7:58 am
by simonmlewis
Garrghhh annoying isn't the word.
So I have tried to alter my upload script but it doesn't work locally either.

This is the bit I had to tweak - have I done it wrong?

Code: Select all

if (isset($resize))
{
  if ($resize == "categories" || $resize == "products")
  {
    // An array of widths, keyed by target screen size
$widths = array(
    '475' => 237,
    '768' => 384,
    '1920' => 451,
);
  }
  elseif ($resize == "wide")
  {
  // An array of widths, keyed by target screen size
$widths = array(
    '475' => 237,
    '768' => 384,
    '1920' => 950,
);
  }
  elseif ($resize == "desktopslide")
  {
  // An array of widths, keyed by target screen size
$widths = array(
    '475' => 475,
    '768' => 768,
    '1920' => 1920,
);
  } 
  return $widths; 
}

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

Posted: Mon Mar 13, 2017 8:00 am
by simonmlewis
Sorry to be jumping around.
So I think the tasks here are
1) get the upload to work with the new (or old!) array() script.
2)I think Glob was getting upset because the database had the image on it, but the file didn't exist. Not sure why but we can step into that.
3) how do we test that the require_once file is there?

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

Posted: Mon Mar 13, 2017 8:01 am
by Celauran
I see a return statement there, but I don't see a function. Are you trying to change things locally simply to solve the issues on the live (sandbox?) server? Or were there things that weren't working locally either?

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

Posted: Mon Mar 13, 2017 8:03 am
by simonmlewis
Exactly. Trying to make it work locally, with the () style of script, but I tweaked it uploaded it and it failed. Made the mistake of not checking here.

ps not feeling well today, so that's why my head did some silly things!

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

Posted: Mon Mar 13, 2017 8:04 am
by Celauran
simonmlewis wrote:Sorry to be jumping around.
So I think the tasks here are
1) get the upload to work with the new (or old!) array() script.
2)I think Glob was getting upset because the database had the image on it, but the file didn't exist. Not sure why but we can step into that.
3) how do we test that the require_once file is there?
Let's start with 3. This is on a different server, yes? Why not just upload a test file with the following:

Code: Select all

<?php

require_once __DIR__ . '/vendor/autoload.php';

$imagine = new Imagine\Gd\Imagine();
var_dump($imagine);
See what sort of output you get from that. (And again, mind the require path as it may not match your server setup)

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

Posted: Mon Mar 13, 2017 8:05 am
by simonmlewis
[text]object(Imagine\Gd\Imagine)#2 (2) { ["info":"Imagine\Gd\Imagine":private]=> array(12) { ["GD Version"]=> string(27) "bundled (2.0.34 compatible)" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPEG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XPM Support"]=> bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) } ["metadataReader":"Imagine\Image\AbstractImagine":private]=> NULL } [/text]
This good?

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

Posted: Mon Mar 13, 2017 8:06 am
by Celauran
simonmlewis wrote:Exactly. Trying to make it work locally, with the () style of script, but I tweaked it uploaded it and it failed. Made the mistake of not checking here.
Let's take a step back, then. What happened to the function call? That's still the best technique to employ as it's the most easily re-used. We can tweak the inner workings of the function a little if we need to, but let's be careful not to undo what we had achieved last week. Can you roll it back to a last known good state and we'll work through the modifications needed to get it working on 5.3?

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

Posted: Mon Mar 13, 2017 8:07 am
by Celauran
simonmlewis wrote:[text]object(Imagine\Gd\Imagine)#2 (2) { ["info":"Imagine\Gd\Imagine":private]=> array(12) { ["GD Version"]=> string(27) "bundled (2.0.34 compatible)" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPEG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XPM Support"]=> bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) } ["metadataReader":"Imagine\Image\AbstractImagine":private]=> NULL } [/text]
This good?
Yes. That means the Composer autoloader is being found and loaded and you've got a working instance of Imagine. This effectively rules out Composer as a culprit in any of this.

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

Posted: Mon Mar 13, 2017 8:12 am
by simonmlewis
Celauran wrote:
simonmlewis wrote:Exactly. Trying to make it work locally, with the () style of script, but I tweaked it uploaded it and it failed. Made the mistake of not checking here.
Let's take a step back, then. What happened to the function call? That's still the best technique to employ as it's the most easily re-used. We can tweak the inner workings of the function a little if we need to, but let's be careful not to undo what we had achieved last week. Can you roll it back to a last known good state and we'll work through the modifications needed to get it working on 5.3?
That's good about Composer.

This is the Function.

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;
      case 'thumbnails':
      $actualfolder = 'productphotos/small';
      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, $actualfolder);
                $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();
    
  switch($resize_type) {
      case 'stockbanners':
      $actualfolder = 'stockbanners';
      break;
      case 'thumbnails':
      $actualfolder = 'productphotos/small';
      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, $save_path)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $save_path;
    $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);
}

?>
I had to add a new set for the Product Photo Thumbnails. For their location and size.
Then I went to test on live and you told me about the () requirements. So I added that.
But the Resize tool when admin upload a photo doesn't use this.

If I add the function include to my categ.inc file, that WORKS. I see the images being generated, and the page loads up.

So I think we need to resolve the Upload tool.

Code: Select all

// ADD ALL BANNERS (SQUARE AND DOUBLE)
if ($update == "addbanner")
{
  if (isset($layertype))
  {
    $result = mysql_query ("SELECT id FROM products WHERE romancode = '$searchurl'");
    $num_result = mysql_num_rows($result);
    if ($num_result > 1)
    {
    $disableupload = "yes";
    echo "<script>
  window.location.replace('/a_home&status=duplicatecode')
  </script>";
    }
  }
 
  if (!isset($disableupload))
  {
    if ($stockbanner == "yes")
    {
      if ($searchurl != "")
      {
      mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      elseif ($searchurl == "")
      {
      mysql_query("INSERT INTO homepage (url, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
      }
      echo "<script>
  window.location.replace('/a_home')
  </script>";
    }
    else
    {
    $target_directory = $_SERVER['DOCUMENT_ROOT']."/images/pages/";
    $random = (rand()%99999999);
    $pic=($_FILES['homeimage']['name']);
    $newname= $random . "_". $pic;
    $target = $target_directory . $newname;
    if ($searchurl != "")
  {
  mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$searchurl', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
  elseif ($searchurl == "")
  {
  mysql_query("INSERT INTO homepage(url, image, section, freetext, priority, content, homepromocolor, homepromotextcolor, stockbanner) VALUES ('$url', '$newname', '$section', '$freetext', '$priority', '$content', '$homepromocolor', '$homepromotextcolor', '$stockbanner')");
  }
 
require_once dirname(__DIR__) . '/vendor/autoload.php';
$imagine = new Imagine\Gd\Imagine();

if (isset($resize))
{
  if ($resize == "categories" || $resize == "products")
  {
    // An array of widths, keyed by target screen size
$widths = array(
    '475' => 237,
    '768' => 384,
    '1920' => 451,
);
  }
  elseif ($resize == "wide")
  {
  // An array of widths, keyed by target screen size
$widths = array(
    '475' => 237,
    '768' => 384,
    '1920' => 950,
);
  }
  elseif ($resize == "desktopslide")
  {
  // An array of widths, keyed by target screen size
$widths = array(
    '475' => 475,
    '768' => 768,
    '1920' => 1920,
);
  } 
  return $widths; 
}

// If we have an uploaded image without errors
if (!empty($_FILES) && isset($_FILES['homeimage'])) {

    // Resize
    foreach ($widths as $key => $width) {
    $pathinfo = pathinfo($_FILES['homeimage']['name']);

    // Open the uploaded image with the Imagine library
    $image = $imagine->open($_FILES['homeimage']['tmp_name']);

    // Get image size
    $box = $image->getSize();
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        
        $new_filename = "{$random}_{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename, array('jpeg_quality' => 95));
    }
}
  //Writes the photo to the server
  if(move_uploaded_file($_FILES['homeimage']['tmp_name'], $target))
    {
echo "<script>
  window.location.replace('/a_home')
  </script>";
    }
  }
}}
}

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

Posted: Mon Mar 13, 2017 8:20 am
by Celauran
So the functions page still has short array syntax in a number of places, so that will definitely need to be fixed.

The upload file also appears to have some duplication with the functions page. Let's try to remove that duplication, use the functions page, and minimize the number of places we need to make changes. (Also, can we give these files names so we know we're talking about the same thing?)

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

Posted: Mon Mar 13, 2017 8:23 am
by Celauran
Functions file quickly cleaned up:

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 = array('jpeg_quality' => 97);
            break;
        case 'png':
            $options = array('png_compression_level' => 8);
            break;
        default:
            $options = array();
    }

    return $options;
}

function getSrcSet($filename, $resize_type = 'wide')
{
    // This can probably be extracted to a function
    switch($resize_type) {
        case 'stockbanners':
            $actualfolder = 'stockbanners';
            break;
        case 'thumbnails':
            $actualfolder = 'productphotos/small';
            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 = array();

    $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, $actualfolder);
                $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();

    // Duplication from above. This is why we extract things to functions
    switch($resize_type) {
        case 'stockbanners':
            $actualfolder = 'stockbanners';
            break;
        case 'thumbnails':
            $actualfolder = 'productphotos/small';
            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, $save_path)
{
    $imagine = new Imagine\Gd\Imagine();

    $target_directory = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $save_path;
    $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: Mon Mar 13, 2017 8:27 am
by Celauran
Celauran wrote:The upload file also appears to have some duplication with the functions page.
For example:

Code: Select all

// Why not use getWidths($resize) ?
if (isset($resize)) {
    if ($resize == "categories" || $resize == "products") {
        // An array of widths, keyed by target screen size
        $widths = array(
            '475' => 237,
            '768' => 384,
            '1920' => 451,
        );
    } elseif ($resize == "wide") {
        // An array of widths, keyed by target screen size
        $widths = array(
            '475' => 237,
            '768' => 384,
            '1920' => 950,
        );
    } elseif ($resize == "desktopslide") {
        // An array of widths, keyed by target screen size
        $widths = array(
            '475' => 475,
            '768' => 768,
            '1920' => 1920,
        );
    }
    // return $widths;
}

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

Posted: Mon Mar 13, 2017 8:29 am
by Celauran
Do you see how this is basically just resizeImage?

Code: Select all

// If we have an uploaded image without errors
if (!empty($_FILES) && isset($_FILES['homeimage'])) {

    // Resize
    foreach ($widths as $key => $width) {
        $pathinfo = pathinfo($_FILES['homeimage']['name']);

        // Open the uploaded image with the Imagine library
        $image = $imagine->open($_FILES['homeimage']['tmp_name']);

        // Get image size
        $box = $image->getSize();
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);

        $new_filename = "{$random}_{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename, array('jpeg_quality' => 95));
    }
}

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

Posted: Mon Mar 13, 2017 8:32 am
by simonmlewis
I think so. But my head isn't as *with it* today as it was last week.