Brian Scramlin

How Image Resizing Works

Recommended Posts

Hey Everyone,

I have a question that seems like it would have an obvious answer, but I cannot wrap my mind around it:

If I have 

<img src="<?= $page->featuredImage->size(800,500)->url ?>"/>

in an article template, does my server run a resizing script

  • every time someone requests the page?
  • Or, is it resized only the first time it is requested?
  • Or when the page is saved?

The reason I would like to know is because I have created two image processing functions my client requires, but one of them is a paid subscription service to compress the images. I don't want to call the paid API every time a page is loaded or something.

Thanks for fielding my ignorance :P

Share this post


Link to post
Share on other sites

The thumbnail generation does run when this code is executed and the file corresponding to the thumbnail does not exist at that time.

  • Like 1

Share this post


Link to post
Share on other sites

How is it possible for me to run a PHP Function on an image as it is being uploaded? This would be the ideal situation because then anywhere I need to execute the ->size() functions I don't have to re-call my compression service.

Right now all over my website I have something like  tinify($page->image->size(200,200)->url) instead I would rather just have the tinify() function called on the initial save. 

Further, if it was possible to do this for every image including CKEditor body images we would be in business!

Thank you for your help. 

Share this post


Link to post
Share on other sites

There are various topics around this exact use case on the forums. The short version: there's no obvious solution, but things you can do.

Share this post


Link to post
Share on other sites
1 hour ago, Brian Scramlin said:

How is it possible for me to run a PHP Function on an image as it is being uploaded? This would be the ideal situation because then anywhere I need to execute the ->size() functions I don't have to re-call my compression service.

Right now all over my website I have something like  tinify($page->image->size(200,200)->url) instead I would rather just have the tinify() function called on the initial save. 

Further, if it was possible to do this for every image including CKEditor body images we would be in business!

Thank you for your help. 

Tinifying images is ONLY useful on the final variations. Tinifying an original source image is completly WRONG.

This tinifying is often misunderstood.

You can resize an image on upload to variuos varirations and also tinify them, if you exactly know which variations you will need around in your site.

Here is an example how to hook into upload and process something with the image:

 

  • Like 2

Share this post


Link to post
Share on other sites

Thank you, everyone. I appreciate your input. I understand in most scenarios converting the original file on upload is not the best approach. However, in this situation it seems the best way to save on calling my iMagick function and compression function. 

First off, I have never created a Processwire module and am intimidated by the prospect, but I am considering the suggested InputfieldImageThumbs module route.

Here is the original module:

class InputfieldImageThumbs extends WireData implements Module {

    public function init() {
        $this->addHookAfter('InputfieldFile::fileAdded', $this, 'createThumbs');
    }

    public function createThumbs($event) {
        $inputfield = $event->object;
        $image = $event->arguments("pagefile");
        
        $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF); // allowed image formats
        $detectedType = exif_imagetype($image->filename); // check if file is an image
        if(!in_array($detectedType, $allowedTypes)) return; // if not, exit

        $widths = explode(",", $this->imageWidths, 10); // convert comma separated list to array, limit to 10 values
        $widths = array_filter($widths, 'ctype_digit'); // keep only numeric entries in the array
        
        foreach($widths as $width) {
            $image->size($width,0); // generate image for each defined width
        }
    }
}

Here is a stab at my attempted module. I am very new at this, so please prepare yourself

class tinifyImages extends WireData implements Module {

    public function init() {
        $this->addHookAfter('InputfieldFile::fileAdded', $this, 'tinify');
    }

    public function tinify($event) {
        $inputfield = $event->object;
        $image = $event->arguments("pagefile");
        
        $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF); // allowed image formats
        $detectedType = exif_imagetype($image->filename); // check if file is an image
        if(!in_array($detectedType, $allowedTypes)) return; // if not, exit

        /* Include Tinify API Resources and Initialize */
        require_once("inc/tinify-php-master/lib/Tinify/Exception.php");
        require_once("inc/tinify-php-master/lib/Tinify/ResultMeta.php");
        require_once("inc/tinify-php-master/lib/Tinify/Result.php");
        require_once("inc/tinify-php-master/lib/Tinify/Source.php");
        require_once("inc/tinify-php-master/lib/Tinify/Client.php");
        require_once("inc/tinify-php-master/lib/Tinify.php");
        \Tinify\setKey("API_KEY");

        //function used to compress with tinify api 
        function tinify($imagePath) {
            $path_parts = pathinfo($imagePath);
            $dirname = $path_parts['dirname'] . '/';
            $filename = $path_parts['filename'];
            $savename = $dirname . $filename . '-compressed.jpg';
            if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $savename)) {
                $source = \Tinify\fromFile($_SERVER['DOCUMENT_ROOT'] . $imagePath);
                $source->toFile($_SERVER['DOCUMENT_ROOT'] . $savename);
            }
            return $savename;
        }
        
        $image = tinify($image->url);
    }
}
?>

Am I close?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By chuckymendoza
      Hello together,
      I have a problem with the image field and in my case it seems that there is a limit of how much images can be in such field.
      The following case:
      I have around 20 pages. Each has a usual image field, where I can upload an unlimited number of images (array).
      Most of the pages got 50-200 images but one page got 411 images (I know, it’s much  )

      Now, when I change the order of one image (let’s say I drag & Drop the first image after the third) or delete one image by clicking on the trashcan, everything runs fine. BUT when I click SAVE the image won’t be deleted or moved to it’s new place. You can change anything else on the page - I have a text field there - and save it, no problem.
      Interestingly I can add (upload) new images but I’m not able to delete or move them.
      - The file size of the images are between 200kb and 1.7MB, RGB, JPGs.
      - When I duplicate the page and try to delete/move I got the same problem.
      - I also created a whole new page and got the same problem
      - Also tried a different server (virtual and online): same problem
      - ProcessWire 3.0.62
      So, is there a limited to the images field? Any clues except limiting the image files to max. +-200 images?
       
      Thanks so much in advance and have a great weekend.
      Thomas
    • By ridgedale
      Reference: PW 3.0.62 and uikit3 based site using the Regular-Master profile.
      I wonder if anyone has come across the problem of displaying images within the <figure> element before.
      When editing a page:
      If an image is added inside <p></p> tags without any align assigned, it displays normally at the size the user has specified. See screen grab example 1.
      If an image is placed inside the <figure> element and left or right alignment applied, the size the image is displayed as in the editing view is significantly reduced. See screen grab example 2.
      If an image is placed inside the <figure> element and center alignment applied, the size the image completely disappears in the editing view with only the caption text showing. See screen grab example 3.
      The code used to display an image in <p></p> tags without aligment assigned is standard:
      <p><img alt="" src="/<path-to-image>/image.jpg" width="128" /></p> Examples of the code automatically being generated by PW3/UiKit3 from within the image editing interface are:
      <figure class="align_left"><img alt="" src="/<path-to-image>/image.jpg>" width="128" /> <figcaption>Caption text</figcaption> </figure> <figure class="align_right"><img alt="" src="/<path-to-image>/image.jpg>" width="128" /> <figcaption>Caption text</figcaption> </figure> <figure class="align_center"><img alt="" src="/<path-to-image>/image.jpg>" width="128" /> <figcaption>Caption text</figcaption> </figure> Important Note: The images and and captions actually do display correctly when the website is browsed, but from the editing perspective it is not practical.
      Any thoughts or advice would be appreciated.



    • By jploch
      Hi!
      I have a problem with uploading animated GIFs again.
      The upload starts, but never finishes and just loads forever.
      Iam running PW 3.0.62 and have the Image Animated GIF Module installed.

      I also increased the memory limit in the htaccess file in PW root directory like this:
      <IfModule mod_php5.c>
      php_value memory_limit 256
      php_value upload_max_filesize 64M
      php_value post_max_size 64M
      php_value max_execution_time 300
      php_value max_input_time 1000
      </IfModule> 
      I had this problem before, but was able to fix it with the Animated GIF Module and the modification of the htaccess file.
      So maybe this is related to the provider (strato).
      Here is the error I get, when uploading the GIF (1.1 MB filesize)
      Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/wire/core/PWGIF.php on line 252 Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/site/assets/cache/FileCompiler/site/modules/ImageAnimatedGif/ImageAnimatedGif.module on line 285 Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/wire/core/PWGIF.php on line 252 Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/wire/core/PWGIF.php on line 252 Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/site/assets/cache/FileCompiler/site/modules/ImageAnimatedGif/ImageAnimatedGif.module on line 285 Warning: preg_match_all() expects at least 3 parameters, 2 given in /mnt/web216/a2/50/51925650/htdocs/processwire/wire/core/PWGIF.php on line 252 [{"error":false,"message":"Added file: test.gif","file":"\/processwire\/site\/assets\/files\/1098\/test.gif","size":101734,"markup":"<li id='file_daf280af792fd5b906511363ae2bc39d' class='ImageOuter gridImage ui-widget'><div class='gridImage__tooltip'><table><tr><th>Dimensions<\/th><td>500x333<\/td><\/tr><tr><th>Filesize<\/th><td>99&nbsp;kB<\/td><\/tr><tr><th>Variations<\/th><td>0<\/td><\/tr><\/table><\/div>\n\t\t\t<div class='gridImage__overflow'>\n\t\t\t\t<img src=\"\/processwire\/site\/assets\/files\/1098\/test.0x260.gif?nc=1509109293\" alt=\"\" data-w=\"500\" data-h=\"333\" data-original=\"\/processwire\/site\/assets\/files\/1098\/test.gif?nc=1509109293\" \/>\n\t\t\t<\/div>\n\t\t\t\n\t\t\t\t<div class='gridImage__hover'>\n\t\t\t\t\t<div class='gridImage__inner'>\n\t\t\t\t\t\t<label for='' class='gridImage__trash'>\n\t\t\t\t\t\t\t<input class='gridImage__deletebox' type='checkbox' name='delete_thumbnail_daf280af792fd5b906511363ae2bc39d' value='1' title='Delete' \/>\n\t\t\t\t\t\t\t<span class='fa fa-trash-o'><\/span>\n\t\t\t\t\t\t<\/label>\n\t\t\t\t\t\t<a class='gridImage__edit'>\n\t\t\t\t\t\t\t<span>Edit<\/span>\n\t\t\t\t\t\t<\/a>\n\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\n\t\t\t\t<div class='ImageData'>\n\t\t\t\t\t<h2 class='InputfieldImageEdit__name'><span contenteditable='true'>test<\/span>.gif<\/h2>\n\t\t\t\t\t<span class='InputfieldImageEdit__info'>99&nbsp;kB, 500&times;333 <\/span>\n\t\t\t\t\t<div class='InputfieldImageEdit__errors'><\/div>\n\t\t\t\t\t<div class='InputfieldImageEdit__buttons'><small><button type='button' data-href='\/processwire\/admin\/page\/image\/edit\/?id=1098&file=1098,test.gif&rte=0&field=thumbnail' class='InputfieldImageButtonCrop ui-button ui-corner-all ui-state-default pw-modal-large pw-modal' data-buttons='#non_rte_dialog_buttons button' data-autoclose='1' data-close='#non_rte_cancel'><span class='ui-button-text'><span class='fa fa-crop'><\/span> Crop<\/span><\/button><button type='button' data-href='\/processwire\/admin\/page\/image\/variations\/?id=1098&file=test.gif&modal=1&varcnt=varcnt_thumbnail_daf280af792fd5b906511363ae2bc39d' class='ui-button ui-corner-all ui-state-default pw-modal-large pw-modal' data-buttons='button'><span class='ui-button-text'><span class='fa fa-files-o'><\/span> Variations <span class='ui-priority-secondary'>(0)<\/span><\/span><\/button><\/small><\/div>\n\t\t\t\t\t<div class='InputfieldImageEdit__core'><div class='InputfieldFileDescription'><label for='description_thumbnail_daf280af792fd5b906511363ae2bc39d' class='detail'>Description<\/label><input type='text' name='description_thumbnail_daf280af792fd5b906511363ae2bc39d' id='description_thumbnail_daf280af792fd5b906511363ae2bc39d' value='' \/><\/div><\/div>\n\t\t\t\t\t<div class='InputfieldImageEdit__additional'><\/div>\n\t\t\t\t\t<input class='InputfieldFileSort' type='text' name='sort_thumbnail_daf280af792fd5b906511363ae2bc39d' value='1' \/>\n\t\t\t\t\t<input class='InputfieldFileReplace' type='hidden' name='replace_thumbnail_daf280af792fd5b906511363ae2bc39d' \/>\n\t\t\t\t\t<input class='InputfieldFileRename' type='hidden' name='rename_thumbnail_daf280af792fd5b906511363ae2bc39d' \/>\n\t\t\t\t<\/div>\n\t\t\t<\/li>","replace":true,"overwrite":0}]  
    • By mike62
      I am new to PW, and am trying to get an image to display, from a field in my template. Here's the code I'm using:
      <?php $image = $page->home_header_image; echo "<img src='{$image->url}' alt='{$image->description}' />"; ?> I'm following the tutorial on this here.
      When I save the template and reload the page, the path to the image is incomplete. If just echoes:
      <img src="/site/assets/files/1/" alt=""> It omits the name of the image, at the end of the path.
      Here's the site I'm working on:
      http://dev.delucaswpg.webfactional.com
      A couple caveats:
      I'm using ProcessWire 2.3.0 (tried updating the site and everything went berserk because of some plugin dependencies; point being: I can't update to the latest PW). I tried using the ->size thing and it gave me an error, saying it couldn't use 'size' in this context. Which I also thought was weird. Any ideas? Thanks!
    • By prestoav
      Hi all,
      PW: 3.0.42
      I'm trying to have responsive images in the body field. First I need to stop the image tag generated by CKEditor adding the width attribute to the image tag on insertion. I found the 'Skip width attributes on image tags?' in the settings of ProcessPageEditImage and that suggests it does exactly what I'm after.
      Sadly, even when this checkbox is checked and a new image is inserted the width attribute is still added.
      Am I missing something?
      TIA.