Page 33 of 37

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

Posted: Tue Mar 14, 2017 11:14 am
by simonmlewis

Code: Select all

// 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($save_path);
    // 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($source_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);
    $archiveDeletefile = $target_directory . DIRECTORY_SEPARATOR . $original;
    if (file_exists($archiveDeletefile))
    {
    // Open the uploaded image with the Imagine library
    unlink($archiveDeletefile);
    }
}
This? Though if the new files are already there, would this still be used?

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

Posted: Tue Mar 14, 2017 11:15 am
by Celauran
simonmlewis wrote:So I can add something in getSrcSet to see if it is doing the whole process to create the new images.
If it is, then what? make it run the deletion from in there? Considering it has all the filename and directory there.

But if it is NOT using that, because the newly _475... images have been made, I could put it where..?
I recommended getSrcSet because you know that's going to be called frequently, perhaps removing the need for a one-off script or a cron job. Where in that function you place it is up to you. Could the thumbnail exist even if the full sized image doesn't? Then you can call it as soon as you have the thumbnail path.

Code: Select all

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

    $paths = getPaths($resize_type);
    $fullsize_directory = $root_directory . $paths['fullsize'];
    $thumbnail_directory = $root_directory . $paths['thumbnail'];

    // Cleanup any old thumbnails that may be lying around
    if ($resize_type === 'thumbnails') {
        $old_thumbnail = $thumbnail_directory . DIRECTORY_SEPARATOR . $filename;
        if (file_exists($old_thumbnail)) {
            unlink($old_thumbnail);
        }
    }

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

    $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);
}
If it can't, then call it once you have ascertained that the full sized image exists.

Code: Select all

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

    $paths = getPaths($resize_type);
    $fullsize_directory = $root_directory . $paths['fullsize'];
    $thumbnail_directory = $root_directory . $paths['thumbnail'];

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

    $widths = getWidths($resize_type);

    if (file_exists($fullsize_directory . DIRECTORY_SEPARATOR . $filename)) {
        if ($resize_type === 'thumbnails') {
            $old_thumbnail = $thumbnail_directory . DIRECTORY_SEPARATOR . $filename;
            if (file_exists($old_thumbnail)) {
                unlink($old_thumbnail);
            }
        }

        $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);
}
Finally, if you want to extract a separate function, you could do something like this

Code: Select all

function deleteFile($path)
{
    if (is_file($path)) {
        unlink($path);
    }
}

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

    $paths = getPaths($resize_type);
    $fullsize_directory = $root_directory . $paths['fullsize'];
    $thumbnail_directory = $root_directory . $paths['thumbnail'];

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

    $widths = getWidths($resize_type);

    if (file_exists($fullsize_directory . DIRECTORY_SEPARATOR . $filename)) {
        if ($resize_type === 'thumbnails') {
            deleteFile($thumbnail_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);
}
Truth is it's all basically the same.

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

Posted: Tue Mar 14, 2017 11:15 am
by Celauran
simonmlewis wrote:

Code: Select all

// 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($save_path);
    // 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($source_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);
    $archiveDeletefile = $target_directory . DIRECTORY_SEPARATOR . $original;
    if (file_exists($archiveDeletefile))
    {
    // Open the uploaded image with the Imagine library
    unlink($archiveDeletefile);
    }
}
This? Though if the new files are already there, would this still be used?
That will work but will not be called if the new images already exist.

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

Posted: Tue Mar 14, 2017 11:16 am
by Celauran
simonmlewis wrote:It couldn't run off cron, as I need it to delete them ONLY if the new ones are in place.
Do you? New ones are generated on the fly anyway.

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

Posted: Tue Mar 14, 2017 11:20 am
by simonmlewis
There will ONLY be a small version, if there is a large version in the '/images/productphotos' folder.
There will never be one in small, and not in large.

So can you explain why the getSrcSet method would work in the scenario assuming there is one in both those folders (guarantee, not assumption).

I would probably let the old ones just delete as the new ones are developed.
If I do create a Cron to blast the server with around 2800 images to be resized, then yes, it would use this tool to do that.

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

Posted: Tue Mar 14, 2017 11:24 am
by Celauran
simonmlewis wrote:There will ONLY be a small version, if there is a large version in the '/images/productphotos' folder.
There will never be one in small, and not in large.
Careful with never. Doesn't really hurt to check if the file is there and, if it's not, do nothing.
simonmlewis wrote:So can you explain why the getSrcSet method would work in the scenario assuming there is one in both those folders (guarantee, not assumption).
Can you please clarify what you're asking here?
simonmlewis wrote:If I do create a Cron to blast the server with around 2800 images to be resized, then yes, it would use this tool to do that.
I was thinking cron more as a separate job to remove all leftover images, not something tied to generating new ones. Doing both together would also work, of course, but neither is dependent upon the other.

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

Posted: Tue Mar 14, 2017 11:33 am
by Celauran
Pending clarification (in case I misunderstood), here's that function again with comments explaining how it works. Please let me know if that does not adequately clear things up.

Code: Select all

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

    $paths = getPaths($resize_type);
    $fullsize_directory = $root_directory . $paths['fullsize'];
    $thumbnail_directory = $root_directory . $paths['thumbnail'];

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

    $widths = getWidths($resize_type);

    // Does the original image exist?
    if (file_exists($fullsize_directory . DIRECTORY_SEPARATOR . $filename)) {
        // If it does, are we dealing with productphotos? We don't want to
        // accidentally delete a full-sized image from /pages or /stockbanners
        if ($resize_type === 'thumbnails') {
            // File with the same name as the original but in the thumbs directory
            $old_thumbnail = $thumbnail_directory . DIRECTORY_SEPARATOR . $filename;
            // Does this file exist?
            if (file_exists($old_thumbnail)) {
                // Delete it
                unlink($old_thumbnail);
            }
        }

        $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);
}

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

Posted: Tue Mar 14, 2017 11:49 am
by simonmlewis
I got it.
Why does this have three === ?

if ($resize_type === 'thumbnails')

I thought it would just need two. Like:

Code: Select all

<?php
if ($your_name == "simon") { echo "yes";}
?>

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

Posted: Tue Mar 14, 2017 11:54 am
by Celauran
http://php.net/manual/en/language.opera ... arison.php

== checks if two things are equal. === checks if they are identical. This is important because PHP will coerce values when comparing different types.
Consider the following:
[text]12:51 ~/Code/Sites/DevNet
❯ php -a
Interactive shell

php > var_dump(0 == "");
bool(true)
php > var_dump(0 === "");
bool(false)
php >[/text]

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

Posted: Tue Mar 14, 2017 12:38 pm
by simonmlewis
Ok ta.
Quick question about srcset. If I have an IMG tag, with the original fiile, and then the three versions for 475, 768 and 1920, but the user is on a 4K screen, should it not serve up the original file instead of the 1920?

For some reason, that's what's happening and it looks out of focus as it is showing a 451px wide image, stretched.

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

Posted: Tue Mar 14, 2017 12:50 pm
by Celauran
I would expect so, yes. Testing here, that is what's happening. Checking in Firefox's responsive design mode set to 4K, I get back the original 3840x2160 image I had uploaded. Have you checked that the original itself is properly sized?

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

Posted: Tue Mar 14, 2017 12:52 pm
by simonmlewis
if I test this site locally on chrome using it's dev tools at 2520, it shows the 1920 image.

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

Posted: Tue Mar 14, 2017 1:05 pm
by simonmlewis
May sound basic, but is there a simple HTML code I can use to test this width?
I could create three images with numeric names to dictate what is being shown, to test. Might be something else in my code causing the issue. Tho not sure I could!

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

Posted: Tue Mar 14, 2017 1:33 pm
by simonmlewis

Code: Select all

<img src='original.jpg' srcset='small.jpg 475w, 
medium.jpg 768w, 
medium.jpg 1920w'
 sizes='(max-width: 475px) 475px,
            (max-width: 768px) 768px,
            (max-width: 1920px) 1920px'
  alt= 'logo'/>
If I emulate 2560, I still get the 1920 image.

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

Posted: Tue Mar 14, 2017 1:44 pm
by Celauran
Power outage here. Can't do much from my phone. Also front end isn't my strong suit. Have you tried including width of original in srcset?