d'Hinnisdaël

ImageOptim — automatic image optimization

Recommended Posts

So I decided to wade into module development and created a wrapper module around ImageOptim, a service that compresses and optimizes images in the cloud. ImageOptim currently handles JPG, PNG and GIF files and, depending on the settings you use, shaves off between 15% and 60% in filesize. Great for bandwidth and great for users, especially on mobile.

This module handles the part of uploading images to ImageOptim via their official API, downloading the optimized version and storing it alongside the original image.
 

ImageOptim.png

 

Download & Info

GitHub / Module directoryReadme / Usage
 

Why ImageOptim?

There are other image optimization services out there, some of them free, that have outstanding ProcessWire modules. A few things make ImageOptim the best tool for most of my customers: It's not free, i.e. it will probably be around for a while and offers support. However, it's cheaper than some of the bigger competitors like Cloudinary. And it does PNG compression better than any of the free services out there, especially those with alpha channels.
 

Installation

Install the module like any other ProcessWire module, by either copying the folder into your modules folder or installing it via the admin. See above for downloads links on GitHub and in the module directory.
 

Requirements

To be able to upload images to the service, allow_url_fopen must be set on the server. The module will abort installation if that's not the case.

I have only tested the module on ProcessWire 3.x installations. I don't see why it shouldn't work in 2.x, if anyone wants to try it out and report back.
 

ImageOptim account

To compress images, you first need to sign up for an ImageOptim account. They offer free trials to try the service.
 

Usage (manual optimization)

Images can be optimized by calling the optimize() method on any image. You can pass an options array to set ImageOptim API parameters.

$image->size(800,600)->optimize()->url
$image->optimize(['quality' => 'low', 'dpr' => 2]) // Set quality to low and enable hi-dpi mode


Automatic optimization

The module also has an automatic mode that optimizes all image variations after resizing. This is the recommended way to use this module since it leaves the original image uncompressed, but optimizes all derivative images.

$image->size(800,600)->url // nothing to do here; image is optimized automatically


To change compression setting for single images, you can pass an options array along with the standard ImageResizer options. Passing false disables optimization.

$image->size(800, 600, ['optimize' => 'medium'])
$image->size(800, 600, ['optimize' => ['quality' => 'low', 'dpr' => 2]])
$image->size(800, 600, ['optimize' => false])


For detailed usage instructions and all API parameters, see the usage instructions on GitHub.
 

Filenames

Optimized images will be suffixed, e.g. image.jpg becomes image.optim.jpg. You can configure the suffix in the module settings.
 

Roadmap

  • Asynchronous processing. Not really high on the list. Image variations need to be created anyway, so waiting a few seconds longer on first load is preferable to adding complexity to achieve async optimization.
  • Optimize image variations created by other modules. CroppableImage comes to mind. I don't use any of these, so if somebody wants to help out and submit a pull request — all for it!
  • Add a dedicated page in the setup menu with a dashboard and detailed statistics. ImageOptim's API is very barebones for now, so not sure if that's feasible or even necessary.


Stability

I've been using this module on production sites for some time now, without hiccups. If you do notice oddities, feel free to comment here or investigate and submit PRs.

  • Like 11
  • Thanks 2

Share this post


Link to post
Share on other sites

Hi @d'Hinnisdaël,

many thanks for this well crafted module. ^-^

I (only) have read the modules code and checked some, (maybe critical) points for image modules ;). Everything seems to be well done! Only one thing I spotted, needs a bit clarification from you, as I may not see the whole picture yet.

You added a new hook delete to Pageimage. I cannot see how this integrates with PW's methods for deleting variations. How gets it invoked when I a) delete an image via UI and b) when I call removeVariations() via the API? Or what is it for, exactly?

Besides the integration with unlink & removeVariations, it may be very useful to have a function that only removes the variations from ImageOptim!

 

TL;DR

Spoiler

One possible solution, or the recommended one for this, would be to hook into isVariation(), as this is invoked from all PW functions (unlink, removeVariations).

If you don't want to use a semantically compatible suffix with your variations, you need to hook into this and have to keep track of adding the variations from this module to the methods result.

Or, if you change the none conform suffix to a supported one, you have to do nothing in this regard, (also don't need to add a hook delete), as it all is done from within PW.


// none conform
basename.optim.0x260-suffix1-suf2.ext

// PW conform
basename.0x260-optim-suffix1-suf2.ext
basename.0x260-suffix1-optim-suf2.ext
basename.0x260-suf2-suffix1-optim.ext

My concern is, if you do it like I understand it now, it may result in lots of lost variations across the assets/files directories when people use removeVariations(), what also is called by manually deleting images in the UI.


 

  • Like 7

Share this post


Link to post
Share on other sites

Dear @horst,

thanks for the valuable feedback.

Indeed you mentioned a very good point. I suspect I had a slightly different than usual understanding of how to remove image variations created by modules. The current implementation uses a glob (/{page folder}/{original file basename}.*) to delete variations.

I'll update the module to use the standard naming scheme — this will have its benefits especially in edge cases, e.g. images will then still get removed if the module is uninstalled or deactivated.

Also good idea about having a public method removeOptimizedVariations(). That will be very easy to implement with the previous issue.

  • Like 7

Share this post


Link to post
Share on other sites

Quick update and version bump to 0.1.0

I updated the module to use the standard ProcessWire variation suffixes. Instead of image.0x200.optim.jpg, optimized images will now be named image.0x200-optim.jpg. Deleting images in the admin or via the API will delete any optimized variations as before, but the process is a lot more straightforward now.

I also added a public method $image->removeOptimizedVariations() that does exactly what it says it does.

  • Like 4
  • Thanks 1

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 blad
      Hi guys!
      I just uploaded a module to explore files based on elFinder. By default it will show the "Files" folder.
      Screenshots:

      Video:
       
      To do:
       More options To fix:
       The function of rotating or scaling an image fails  Image editors V 1.01 (view issue)
      Fixed the bug working with the Multi-Language support ( translation of folders ). Fixed the name of elfinder.en  Github:
      https://github.com/LuisSantiago/ProcessElFinder/
      I hope you like it.
    • By BitPoet
      I'm really in love with FormBuilder, but the one thing missing to match all my end users' expectations were repeatable field groups. Think repeaters, in ProcessWire terms. Our primary application of PW is our corporate intranet, so "lines" of fields are quite common in the forms I build. We have all kinds of request forms where the information for a varying number of colleagues needs to be entered (from meal order to flight booking request) and where it is simply impractical to send a form for each, and I don't want to clutter my forms with multiple instances of fields that may only get used ten percent of the time.
      That's why I started to build FormBuilderMultiplier (link to GitHub).
      What it does:
      Adds an option to make a regular Fieldgroup repeatable Lets you limit the number of instances of a Fieldgroup on the form Adds an "Add row" button the form that adds another instance of the Fieldgroup's fields Adds a counter suffix at the end of every affected field's label Stores the entered values just like regular fields Makes the entered values available in preview and email notifications Supports most text based fields, textareas and selects (really, I haven't had enough time to test all the available choices yet) What it doesn't do (yet):
      Support saving to ProcessWire pages (i.e. real Repeaters) I haven't tested all the validation stuff, Date/Time inputs etc. yet, but since I'm utterly swamped with other stuff at work, I didn't want to wait until I have it polished. Any feedback is welcome. There might also be some issues with different output frameworks that I haven't encountered yet. The forms I work with mostly use UIKit.
      Status:
      Still alpha, so test well before using it in the field.
      Known issues:
      When rows are added, the form's iframe needs to be resized, which isn't completely clean yet.
      How it works:
      The Fieldgroup settings are added through regular hooks, as is the logic that adds the necessary field copies for processing the form and displaying previews.
      "Multiplied" field instances are suffixed with _NUM, where NUM is an incremental integer starting from 1. So if you have add two fields named "surname" and "givenname" to a fieldgroup and check the "multiply" checkbox, the form will initially have "surname_1" and "givenname_1" field (I'm still considering changing that to make the risk to shoot oneself into the foot by having a regular "surname_1" field somewhere else in the form less likely).
      When a "row" is added, the first row is cloned through JS and the counter in the fields' IDs, names and "for" attributes as well as the counter in the label are incremented before appending the copies to the Fieldset container in the form.
      To keep backend and frontend in sync, a hidden field named [name of the fieldset]__multiplier_rows is added to the form. Both the backend and the frontend script use this to store and retrieve the number of "rows".
      ToDo:
      Naturally, add the option to store the data in real repeaters when saving to pages. Do a lot of testing (and likely fixing). Make a few things (like the "Add row" button label etc.) configurable in field(set) context. Add a smooth API to retrieve the multiplied values as WireArrays. The mandatory moving screenshot:

    • By MoritzLost
      Hello there,
      I'm working on a tiny textformatter module that searches the text for titles of other pages on your site and creates hyperlinks to them. I'm not sure if something like this exists already, but I haven't found anything in the module directory, so I wrote my own solution 🙂
      It's not properly tested yet and is still missing some functionality I would like to implement, so at the moment it should be considered in BETA. Features include limiting the pages that will get searched by template, and adding a custom CSS class to the generated hyperlinks. As I'm writing this I noticed that it will probably include unpublished and hidden pages at the moment, so yeah ... it's still in development alright 😅
      You can download the module from Github:
      https://github.com/MoritzLost/TextformatterPageTitleLinks
      There's some more information in the readme as well.
      Anyway, let me know what you think! I'm happy about any feedback, possible improvements or ideas on how to improve the module. Cheers.
    • By adrian
      This module provides a way to rapidly generate Page fields and the required templates and pages for use as a drop down select (or any other Page field type).
      This module will let you create a full page field setup in literally a few seconds 
      To use, run Page Field Select Creator from the Setup Menu
      Enter a Field Title, eg: Room Types Select Options - These will become the child pages that will populate the page field select options. There are two different options.
       
      Option 1. TITLE FIELD ONLY - enter one option per line, eg:
       
      Single
      Double
      Suite
       
       
      Option 2. MULTIPLE FIELDS - the first line is used for the field names and the first field must be 'Title'. Subsequent lines are the values for the fields, eg:
       
      Title, Number of Beds, Number of People, Kitchen Facilities
      Single, 1, 1, Fridge Only
      Double, 2, 2, Fridge Only
      Suite, 3, 6, Full Kitchen
        Choose the parent where the page tree of options will be created, eg a hidden "Options" parent page Select a "Deference in API as" option depending on your needs Choose the input field type Check whether "Allow new pages to be created from field?" should be enabled. As an example, if you entered "Room Types" as the field title, you would end up with all of the following automatically created:
      a fully configured page field called: room_types MULTIPLE FIELDS OPTION - 3 additional fields - number_of_beds, number_of_people, kitchen a parent template called: room_types a child template called: room_types_items (with either just a title field, or with the 3 additional fields as well) a parent page called: Room Types a series of child pages named and titled based on the per line entries in the Select Options textarea The templates are configured such that the "room_types_items" child template can only have the main "room_types" template as a parent, and vice versa.

      Then all you have to do is add the newly created page field to any template you want and you're ready to go!
       
      You can grab it from:
       
      Modules directory: http://modules.processwire.com/modules/process-page-field-select-creator/
      Github: https://github.com/adrianbj/ProcessPageFieldSelectCreator
       

    • By bernhard
      WHY?
      This module was built to fill the gap between simple $pages->find() operations and complex SQL queries.
      The problem with $pages->find() is that it loads all pages into memory and that can be a problem when querying multiple thousands of pages. Even $pages->findMany() loads all pages into memory and therefore is a lot slower than regular SQL.
      The problem with SQL on the other hand is, that the queries are quite complex to build. All fields are separate tables, some repeatable fields use multiple rows for their content that belong to only one single page, you always need to check for the page status (which is not necessary on regular find() operations and therefore nobody is used to that).
      In short: It is far too much work to efficiently and easily get an array of data based on PW pages and fields and I need that a lot for my RockGrid module to build all kinds of tabular data.

      Basic Usage

       
      Docs & Download
      https://modules.processwire.com/modules/rock-finder/
      https://github.com/BernhardBaumrock/RockFinder
       
      Changelog
      180817, v1.0.6, support for joining multiple finders 180810, v1.0.5, basic support for options fields 180528, v1.0.4, add custom select statement option 180516, change sql query method, bump version to 1.0.0 180515, multilang bugfix 180513, beta release <180513, preview/discussion took place here: https://processwire.com/talk/topic/18983-rocksqlfinder-highly-efficient-and-flexible-sql-finder-module/