Image Resizing Script required - a better one...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Do you mean like this?

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' => 100));
    }
}
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post by Celauran »

Is that working for you?
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Yes it has. Perfect. Thanks.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Tho quite bizarrely, an image that was 2520px wide, that was 731kb - has resized to 1920wide, but is also now 1,322kb.
How did it go up??
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post by Celauran »

I have found that setting the quality to 97% results in the same file size. Perhaps more importantly, I don't really notice any difference in image quality at 85%.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Yep that seems to be good. 95% gets it below the original.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

When we go fully live with this, we may need to enable it so it can use the default set image, rather than forcing it to use the srcset image..... as there will be instances where no additional images are uploaded.

Using the srcset <img> code, is there a way of setting it so that if the image is not available, it reverts to the start src="" image??
Alternatively, it would be rather cool if these additionally resized images could be created, on the fly, if they are not available.

That way, the admins won't have to go through them all and re-upload. If it's not on the system, it could resize it.
Tho might for now just be easier if it could revert to the standard image if a srcset is not yet available.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Code: Select all

$file = './images/image.jpg';
if (file_exists($file)) {}
I could perhaps use something like this on the consumer pages.
It would need to run only one, on one of the other files, like _475.
If it does not exist, the others won't either, and it could create them on the fly.
Thing is I don't want someone on a 3G mobile, opening a page, to find that 10 of the smaller images don't exist yet, so it has to wait for that to be processed before displaying it all.

But I think the idea is better than asking the Admins to go thru the whole Re-Uploading process....
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Something along these lines, although this is cause big errors! So I am guessing I have something very wrong here.

Code: Select all

$file = "/images/pages/$row->image";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$filename = pathinfo($file, PATHINFO_FILENAME);

// is the smaller file missing?
$filecheck = $filename . "_475" . $ext;
if (!file_exists($filecheck))
{
  require_once dirname(__DIR__) . '/vendor/autoload.php';
  $imagine = new Imagine\Gd\Imagine();
  $widths = [
    '475' => 237,
    '768' => 384,
    '1920' => 451,
  ];
  // Resize
    foreach ($widths as $key => $width) {
    $pathinfo = pathinfo($row->image);

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

    // Get image size
    $box = $image->getSize();
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        
        $new_filename = "{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename, array('jpeg_quality' => 95));
    }
}

<img srcset='/images/pages/$filename" . "_475" . ".$ext" . " 475w, 
/images/pages/$filename" . "_768" . ".$ext" . " 768w, 
/images/pages/$filename" . "_1920" . ".$ext" . " 1920w'
 sizes='(max-width: 475px) 475px,
            (max-width: 768px) 768px,
            (max-width: 1920px) 1920px'
src='/images/pages/$row->image' alt='$row->freetext'/>
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post by Celauran »

An empty srcset attribute will default to using the image specified in the src attribute. That said, you could write a function that would calculate the srcset values for a given image and echo its return value inside your srcset attribute.

Pseudocode:

Code: Select all

<img src="<?= $image; ?>" srcset="<?= getSrcSet($image); ?>">
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

So if the image isn't even found in the srcset, it will revert to the src file?
What about this idea of resizing on the fly, if the file does not exist? That would be a smart way to do it?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post by Celauran »

Makes sense to me.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

Why would this throw a ton of errors?
Am I making it much more long winded than it needs to be?

Code: Select all

$file = "/images/pages/$row->image";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$filename = pathinfo($file, PATHINFO_FILENAME);

// is the smaller file missing?
$filecheck = $filename . "_475" . $ext;
if (!file_exists($filecheck))
{
  require_once dirname(__DIR__) . '/vendor/autoload.php';
  $imagine = new Imagine\Gd\Imagine();
  $widths = [
    '475' => 237,
    '768' => 384,
    '1920' => 451,
  ];
  // Resize
    foreach ($widths as $key => $width) {
    $pathinfo = pathinfo($row->image);

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

    // Get image size
    $box = $image->getSize();
        $ratio = $width / $box->getWidth();
        $scaled_box = $box->scale($ratio);
        
        $new_filename = "{$pathinfo['filename']}_{$key}.{$pathinfo['extension']}";
        $image->resize($scaled_box)->save($target_directory . '/' . $new_filename, array('jpeg_quality' => 95));
    }
}

echo "<img srcset='/images/pages/$filename" . "_475" . ".$ext" . " 475w, 
/images/pages/$filename" . "_768" . ".$ext" . " 768w, 
/images/pages/$filename" . "_1920" . ".$ext" . " 1920w'
 sizes='(max-width: 475px) 475px,
            (max-width: 768px) 768px,
            (max-width: 1920px) 1920px'
src='/images/pages/$row->image' alt='$row->freetext'/>
<p>$row->freetext</p>";
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

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

Post by Celauran »

That's kind of a mess of spaghetti, isn't it? Look at how much cleaner (and reusable!) my example was. Why not aim for something like that and build it up step by step? It also makes sharing individual bits of code a lot easier as each class or function is self-contained.

As for the errors, let's start with what they are.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

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

Post by simonmlewis »

If the srcset doesn't exist, yet it could return to the original, but that means the admin have to find all those not done, and start work.

If the image is checked on loading, and found to have _475 missing, then it would instantly create it on the fly, and everyone else would then see that image.

The only minor flaw possibly, is if that page has very heavy traffic, then I wonder if it would work so well.

This is the error:
[text]Fatal error: Uncaught exception 'Imagine\Exception\InvalidArgumentException' with message 'File /images/pages/25644881shirt.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('/images/pages/2...')
#1 C:\xampp\phpMyAdmin\site-wide\includes\page.inc(146): Imagine\Gd\Imagine->open('/images/pages/2...')
#2 C:\xampp\phpMyAdmin\site-wide\index.php(42): include('C:\\xampp\\phpMyA...')
#3 C:\xampp\phpMyAdmin\site-wide\index.php(437): getPage(Object(PDO))
#4 {main} thrown in C:\xampp\phpMyAdmin\site-wide\vendor\imagine\imagine\lib\Imagine\Image\AbstractImagine.php on line 72[/text]
A flippin mess.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply