Jump to content

Webp support


jacmaes

Recommended Posts

Should webp extra image get deleted if you replace the original image? That is: upload an image, thumb is generated, then create webp extra by using $myimge->webpurl, then in the admin you replace the image by uploading with the same name eg. replace img1.jpg with img1.jpg. Original image is replaced, thumb is recreated, but webp stay the same. This is how it should be?

webp.gif

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

I first time used $config->pagefileSecure = true; option in config.php. When I echo the image webp extra like this in the template:

echo "<a href='{$img->webpUrl}'>Click to view image</a> ";

and then click on the link, the image can be viewed in the browser, as expected. But when I set pagefileSecure to true, reload the page and click on the link, the image is downloaded. I can see the warning in Chrome console:

Resource interpreted as Document but transferred with MIME type application/octet-stream: "http://localhost/site/assets/files/1015/nature1.webp". 

Also, headers changed to:

Content-disposition: attachment; filename="nature1.webp"
Content-transfer-encoding: binary
Content-Type: application/octet-stream
 
Is this expected or maybe something wrong with my webserver config (IIS)? I didn't change access permissions on the template and also viewing the image logged as admin user.
Link to comment
Share on other sites

  • 1 month later...

Hello to all mighty people and Happy New decade start. Wish you all the greatest goodness, joy and happiness. Well, and a lot of great code as well 😉

I've implemented WEBP images to optimize my soon to be released profile and by a lucky coincidence I discovered on my Mac that no images are showing when using the Safari. I thought that Apple would have embraced the idea by now when several other browsers have already done that but it seemed like I was wrong.

I tested the .htaccess approach, however I could not make it working under Safari, so I decided to add a little function to my _functions.php:

//WEBP Image Support
function webp_support($imgURL)
{
    // Check if the browser headers contain image/webp support
    if(strpos($_SERVER['HTTP_ACCEPT'], 'image/webp')) { 

        // If yes, use the webp image url
        return $imgURL->webp;
    
    } else {

        //Else, show the original image url
        return $imgURL;

    }
}

After that, in every image call I do the following:

<?php
$img = $page->images->first // Call for the image location
$image = webp_support($img->size(100,100)) // Used to size an image and convert it to WEBP

//Image call in the markup
echo "<img src='{$image->url}' alt='{$image->description}' >";

That seems to be working fine and show the WEBP format on Chrome, Opera and Firefox under MacOS/Windows/Linux but show the original image version under Safari. I did not test with the Windows version of Safari since it is a long time not updated version and it won't make much sense to support the newer format anyway.

My question for you is if there is a simpler approach than my current to show WEBP images to the supported browsers and fallback to original If not?

  • Like 2
Link to comment
Share on other sites

For one site I made some time ago I've tried to use the following "official" strategy:

Blogpost from Ryan / May 31, 2019

but, somehow the fallback didn't work on Safari and IE11. I didn't investigate further because I had to deliver the project and until then I've dropped that feature for now.
Your solution looks simple and elegant for me, I couldn't tell the difference against the .htaccess approach (I'm no expert by any mean).

Link to comment
Share on other sites

@MilenKo

Just a minor issue that caught my eyes: I would "cache" the webp support in eg. config.php so it shouldn't be evaluated on each function call:

$config->isWebpSupported = strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false;

if($config->isWebpSupported) {
  // ...

or use a static variable inside the function to evaluate only once:

function webp_support($imgURL)
{
    static $isWebpSupported = strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false;

    if($isWebpSupported) { 
    	// ...
    } else {
        // ...
    }
}

Note that I used "!== false" because if "image/webp" is at the beginning, the strpos gives 0, and it's false (not sure if it can be at 0 position, but it's a good practice to use like this imo).

(untested, haven't written PHP for months :))

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

Thanks @tpr for the static variable and "cache" approaches. I believe that after reading the @teppo detailed instructions about the different approaches, I would start using the <picture></picture> approach for new sites, however would give another try to the automatic webp conversions through .htaccess and code calls in the instructions. I have no doubt that in the next one or two versions, Apple would be having already the WEBP implemented which would simplify the things, however until then, it is good to know the best practices and most important, which way works best for us and users.

Since my profile is fully completed but it is not yet live since I am adding the content now, it won't hurt me to try all the kindly suggested approaches and see for myself which one to keep.

Btw, HAVE AN AMAZING AND PRODUCTIVE 2020 YEAR!

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...
On 1/2/2020 at 6:05 PM, 3fingers said:

For one site I made some time ago I've tried to use the following "official" strategy:

Blogpost from Ryan / May 31, 2019

but, somehow the fallback didn't work on Safari and IE11. I didn't investigate further because I had to deliver the project and until then I've dropped that feature for now.
Your solution looks simple and elegant for me, I couldn't tell the difference against the .htaccess approach (I'm no expert by any mean).

I also had the same trouble with strategy 2. So I switched to strategy 3, wich is a little more effort but better in my opinion. 😉

Regards, Andreas

  • Like 1
Link to comment
Share on other sites

  • 3 months later...

Hi,

i'm trying to add text-watermarks to images placed in a textarea using a textformatter. It works with jpegs executing the function $image->width(123)->watermark('some text') that replaces the variation with a watermarked one. But the webp variation will be created from the original file and there is no watermark. I played a bit with a hook before imSaveReady but the only thing i could achieve, was a watermark on the original file, but here i don't want it.

Has anyone an idea how i can achieve this (using processwire functions and hooks)?

Link to comment
Share on other sites

  • 2 months later...

Good day!

I got a strange issue with webp images on one server. The same image works fine on Firefox and does not show (though blinks for a momдnent when trying to open it) in Chrome. I did regenerate it without luck. Then installed Imagick sizer, regenerated - same thing.

Same code works fine on local machine, generating images readable in both browsers (or serving them in correct way), so must be a server issue. But what could it be? Example image used on this page.

Please help!

  • Like 1
Link to comment
Share on other sites

I can replicate here. There must be something wrong with the image, as it opens in FF and other deskop image viewers on windows. I recreated webp from your original jpg (using online jpg to webp converter) and this time Chronme shows the image. I have no idea what could be wrong, possible Chrome issue?

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

Hi,

Locally I'm using Processwire 3.0.164 on MAMP 4.1.0. with ImageMagick 6.8.9.

The phpinfo lists WEBP under ImageMagick supported format. Nonetheless, ->webp->url is returning a JPG-URL for any image. Why is that?

Link to comment
Share on other sites

Do you have enabled the Imagemagick rendering engine in PW?

pw-enable-imagemagick-render-engine.thumb.jpg.ebb5185c24bda7dd70fac8eabfa031ba.jpg

You also may set strictly use the webp variation, also if the jpeg or png source is smaller in filesize. This is not often the case, but its possible.

site/config.php:

$config->webpOptions = array_merge($config->webpOptions, [
    'quality' => 84,
    'useSrcExt' => false,           // Use source file extension in webp filename? (file.jpg.webp rather than file.webp)
    'useSrcUrlOnSize' => false,     // Fallback to source file URL when webp file is larger than source?
    'useSrcUrlOnFail' => true       // Fallback to source file URL when webp file fails for some reason?
]);

 

  • Like 2
Link to comment
Share on other sites

  • 1 month later...
  • 1 month later...

Hello everybody,

i am currently working on a project where i want to implement the webp support in the code (<picture>...).
But what I'm already busy with all this weekend, that PW for whatever reason doesn't always generate a webp image?

In the first screenshot (which is reproducible) no webp image is generated.

webp-problem.thumb.png.24686674aa3068496fa1ec36b5ffc1ac.png

But if I edit this original picture and change parts of it, then make a jpg out of it and upload it, it works.

webp-ok.thumb.png.d9453323a54e903e9c988678d38ab530.png

Unfortunately, this is not only the case with this picture, but with other pictures this has already happened to me on Friday 😞

Help what could be the reason for this?

-----------

The server specification from my hosting provider
ProcessWire 3.0.165
PHP version 7.4.10

gd module version 2.1.1
WebP Support - enabled

imagick module version 3.4.4
but NO entry in the supported formats!
(that's why I did not enable IMagick Image Sizer)

Link to comment
Share on other sites

  • 4 months later...

Today I again bumped into an issue I had last year with creating WebP images:

Enabling WebP on another project by setting  imageSizerOptions' webpAdd to true immediately resulted in the same behaviour as I had last year: the server simply keeps on creating new variations of images, while they already exist. WebP images are created correctly by the way.

Seems to be a bug, can anybody else confirm? I am using PW Master (3.0.165) on MAMP Pro (MacOS 11.2, PHP 7.4.2)

 

Link to comment
Share on other sites

Hello @eelkenet,

I had that issue on my local MAMP server, when this feature was introduced.

I tried this config option, but for me it doesn't work at all. Is it mandatory to edit your .htaccess?

Because strategies 1 and 2 didn't work for me, I use strategy 3 with an own config variable ($config->useWebP) and disable WebP on my local MAMP server.

Regards, Andreas

  • Thanks 1
Link to comment
Share on other sites

On 4/12/2021 at 5:36 PM, eelkenet said:

Seems to be a bug, can anybody else confirm? I am using PW Master (3.0.165) on MAMP Pro (MacOS 11.2, PHP 7.4.2)

HI @eelkenet,

I have setup a new test site today and it looks that any possible setting is working as expected from the PW image generation site. So it seems I need some more information from your setup.

Especially this:

  • what settings are you using for $config->imageSizerOptions ?
  • what are the settings for $config->webpOptions ?
  • how do you call the image url in your template file(s) with $image->size()->webp->url or $image->size()->url, or how?
    do you use an individually passed options array there?
  • what are your settings in the .htaccess file ?

Please can you provide these information as exact as possible. If you don't want to post this here you can PM me.

My newly set up testing, without any settings in the .htaccess doesn't recreate any variations. It looks like this:

image.thumb.png.921e1684c52d746d6429007a7b4ec2d9.png

  • Like 1
Link to comment
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 Robin S
      Select Images
      An inputfield that allows the visual selection and sorting of images, intended for use with the FieldtypeDynamicOptions module. Together these modules can be used to create a kind of "image reference" field.

      Integration with FieldtypeDynamicOptions
      InputfieldSelectImages was developed to be used together with FieldtypeDynamicOptions (v0.1.3 or newer):
      Create a Dynamic Options field. Choose "Select Images" as the "Inputfield type". Select Images appears in the "Multiple item selection" category but you can set "Maximum number of items" to 1 if you want to use Select Images for single image selections. Define selectable options for the field via a FieldtypeDynamicOptions::getSelectableOptions hook. See some examples below. FieldtypeDynamicOptions is recommended but is not a strict requirement for installing InputfieldSelectImages in case you want to use an alternative way to store the field data.
      Selection of Pageimages
      In this example the field allows selection of Pageimages that are in the "images" field of the home page.
      The field will store URLs to the Pageimages so it works as a kind of "image reference" field. You can use the "Format as Pagefile/Pageimage object(s)" option for the Dynamic Options field to have the formatted value of the field be automatically converted from the stored Pageimage URLs to Pageimage objects.
      $wire->addHookAfter('FieldtypeDynamicOptions::getSelectableOptions', function(HookEvent $event) { // The page being edited $page = $event->arguments(0); // The Dynamic Options field $field = $event->arguments(1); // For a field named "select_images" if($field->name === 'select_images') { $options = []; // Get Pageimages within the "images" field on the home page foreach($event->wire()->pages(1)->images as $image) { // Add an option for each Pageimage // When the key is a Pageimage URL the inputfield will automatically create a thumbnail // In this example the label includes the basename and the filesize /** @var Pageimage $image */ $options[$image->url] = "{$image->basename}<br>{$image->filesizeStr}"; } $event->return = $options; } }); Selection of image files not associated with a Page
      When not working with Pageimages you must add a "data-thumb" attribute for each selectable option which contains a URL to a thumbnail/image.
      In this example the field allows selection of image files in a "/pics/" folder which is in the site root.
      $wire->addHookAfter('FieldtypeDynamicOptions::getSelectableOptions', function(HookEvent $event) { // The page being edited $page = $event->arguments(0); // The Dynamic Options field $field = $event->arguments(1); // For a field named "select_images" if($field->name === 'select_images') { $options = []; // Get files that are in the /pics/ folder $root = $event->wire()->config->paths->root; $path = $root . 'pics/'; $files = $event->wire()->files->find($path); // Add an option for each file foreach($files as $file) { $basename = str_replace($path, '', $file); $url = str_replace($root, '/', $file); // The value must be an array with the following structure... $options[$url] = [ // The label for the image 'label' => $basename, 'attributes' => [ // An image URL in the "data-thumb" attribute 'data-thumb' => $url, ], ]; } $event->return = $options; } }); The field values don't have to be image URLs
      The values stored by the Dynamic Options field don't have to be image URLs. For example, you could use the images to represent different layout options for a page, or to represent widgets that will be inserted on the page.
      Also, you can use external URLs for the thumbnails. In the example below the options "calm" and "crazy" are represented by thumbnails from placecage.com.
      $wire->addHookAfter('FieldtypeDynamicOptions::getSelectableOptions', function(HookEvent $event) { // The page being edited $page = $event->arguments(0); // The Dynamic Options field $field = $event->arguments(1); // For a field named "calm_or_crazy" if($field->name === 'calm_or_crazy') { $options = []; // Add options that are illustrated with thumbnails from placecage.com $options['calm'] = [ // The label for the option 'label' => 'Nicolas Cage is a calm man', 'attributes' => [ // An image URL in the "data-thumb" attribute 'data-thumb' => 'https://www.placecage.com/260/260', ] ]; $options['crazy'] = [ // The label for the option 'label' => 'Nicolas Cage is a crazy man', 'attributes' => [ // An image URL in the "data-thumb" attribute 'data-thumb' => 'https://www.placecage.com/c/260/260', ] ]; $event->return = $options; } }); Field configuration
      You can define labels for the button, notices, etc, that are used within the inputfield if the defaults don't suit.

       
      https://github.com/Toutouwai/InputfieldSelectImages
      https://processwire.com/modules/inputfield-select-images/
    • By Robin S
      Process Images
      A basic, proof-of-concept Textformatter module for ProcessWire. When the Textformatter is applied to a rich text field it uses Simple HTML DOM to find <img> tags in the field value and passes each img node through a hookable TextformatterProcessImages::processImg() method.
      This is a very simple module that doesn't have any configurable settings and doesn't do anything to the field value unless you hook the TextformatterProcessImages::processImg() method.
      Hook example
      When added to /site/ready.php the hook below will replace any Pageimages in a rich text field with a 250px square variation and wrap the <img> tag in a link to the original full-size image.
      For help with Simple HTML DOM refer to its documentation.
      $wire->addHookAfter('TextformatterProcessImages::processImg', function(HookEvent $event) { // The Simple HTML DOM node for the <img> tag /** @var \simple_html_dom_node $img */ $img = $event->arguments(0); // The Pageimage in the <img> src, if any (will be null for external images) /** @var Pageimage $pageimage */ $pageimage = $event->arguments(1); // The Page object in case you need it /** @var Page $page */ $page = $event->arguments(2); // The Field object in case you need it /** @var Field $field */ $field = $event->arguments(3); // Only for images that have a src corresponding to a PW Pageimage if($pageimage) { // Set the src to a 250x250 variation $img->src = $pageimage->size(250,250)->url; // Wrap the img in a lightbox link to the original $img->outertext = "<a class='lightboxclass' href='{$pageimage->url}'>{$img->outertext}</a>"; } });  
      GitHub: https://github.com/Toutouwai/TextformatterProcessImages
      Modules directory: https://processwire.com/modules/textformatter-process-images/
    • By spercy16
      These issues should be fairly easy for any intermediate to advanced ProcessWire developer to answer. I'm new to PHP and relatively new to ProcessWire and just need a bit of help. What I'm trying to do is bring in a couple of cards from my Projects page to display on my home page. I finally got the code right to bring in the cards but right now they're using my original images instead of my resized "variations". So firstly, I would like to know how to reference the variations of my images instead of using the original. Secondly, I need to grab only four of the cards from the Project page and not import in all ten. It should be just two small changes to my code to do these things (I would imagine). Here is the code I currently have for that section:
      <?php // https://processwire.com/api/arrays/ // check if the array of images has items if (count($pages->get("/projects/")->images)) : // get array of images from the field $images = $pages->get("/projects/")->images; $count = 0; // iterate over each one foreach ($images as $image) : $count++; $sectionText = $pages->get("/projects/")->get("paragraph_$count"); $img = $image; $buttonCode = $pages->get("/projects/")->get("url_$count"); ?> <span id="card<?php echo $count?>" class="card"> <img class="cardThumb" src="<?php echo $img->url; ?>" alt="<?php echo $image->description; ?> Thumbnail" /> <div class="cardBody"> <div class="cardText"> <h2><?php echo $img->description; ?></h2> <?php echo $sectionText; ?> </div> <div class="primaryBtn"> <a href="https://www.paypal.com/donate?hosted_button_id= <?php echo $buttonCode; ?> &source=url"> <button> <i class="fas fa-donate"></i> Donate </button> </a> </div> </div> </span> <?php endforeach; endif; ?> Thanks in advance for any help!
    • By skeltern
      WebP image support is great and works fine. But once created I've issues to get rid of all API generated WebP variations.
      The backend image field variations "Delete" works and I can remove all variations JPEG plus WebP. Image list is clean but all WebP API variations are still stored in file system (for instance files/12345/84.900x675.webp etc). I can only use ImageSizer with temp 'force' option to request fresh WebP variations or have to delete WebP files from folders. No other way so far. Tested with 2 sites and latest master PW 3.0.165.
      Is there somewhere a "magic button" or config/setup thing to solve my sticky WebP issue?
    • By psy
      I've searched, and maybe missed, the solution. I have a 'normal' images field and uploading images with a file size greater than 10Kb is fine. Any image size smaller results in the never-ending spinner and no upload.
      No min/max width/height set on image uploads in admin, ie just the defaults.
      Any ideas on how to fix?
      Using:
      PW: 3.0.175
      PHP: 7.3
      Marking it as "Resolved" rather than "Solved" as it auto-magically fixed itself. No idea whether PW, PHP, or just an internet hiccough... All good now 🤞
×
×
  • Create New...