first commit

This commit is contained in:
2024-11-11 18:46:54 +01:00
commit a630d17338
25634 changed files with 4923715 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -0,0 +1 @@
<?php die("Access denied");

View File

@@ -0,0 +1,248 @@
# Stack converter
The stack converter is a mechanism for trying all available converters until success. Well, the default is to try all converters, but this can be configured.
When calling `WebPConvert::convert($source, $destination, $options);`, you are actually invoking the stack converter.
## Passing options down to the individual converters
Any option that you pass to the Stack converter will be passed on to the individual converters. For example, setting options to the following will set the metadata option on all converters:
```php
$options = [
'metadata' => 'all',
];
```
If you need the option to be different for a single converter there are several ways to do it:
#### 1. Prefixing
Options prefixed with a converter id are only effective for that converter, and overrides the non-prefixed option.
Ie, the following will set "metadata" to "all" for all converters, except *cwebp*, where "metadata" is set to "exif"
```php
$options = [
'metadata' => 'all',
'cwebp-metadata' => 'exif'
];
```
Prefixing is by the way a general feature in the way options are handled and thus not confined to the stack converter. (though it admittedly only finds its use in the context of a stack converter).
#### 2. Using the `converter-options` option
The *converter-options* option is convenient for setting a whole bunch of converter-specific options in one go.
Example:
```php
$options = [
'converter-options' => [
'wpc' => [
'crypt-api-key-in-transfer' => true
'api-key' => 'my dog is white',
'api-url' => 'https://example.com/wpc.php',
'api-version' => 1,
],
],
]
```
#### 3. As part of the `converters` option
This option is explained further down this document.
## Modifying the stack
The default stack consists of the following converters:
- cwebp
- vips
- imagick
- gmagick
- imagemagick
- graphicsmagick
- wpc
- ewww
- gd
The order has carefully been chosen based on the capabilities of the converters. It is a rank, if you will.
Now, say that on your system, you only have *gd* working. With the default stack, this means that eight converters will be tested for operationality before getting to *gd* &ndash; each time a conversion is made. You might be tempted to optimizing the flow by putting *gd* on the top. *I would generally advise against this* for the following reasons:
1. It might be that one of the other (and better) converters starts working without you noticing. You will then miss out.
2. All converters have all been designed to exit very quickly when they are not operational. It only takes a few milliseconds for the library to detect that a converter is not operational - literally. For example, if no api key is provided for ewww, it will exit immediately.
However, there are valid reasons to modify the stack. For example, you may prefer *vips* over *cwebp*, or you may wish to remove a converter completely due to problems with that converter on your platform.
### Changing the order of the converters
To change the order, you can use the `preferred-converters` option. With this option you move selected converters to the top of the stack.
So, if you want the stack to start with *vips* and then *ewww*, but keep the rest of the order, you can set the following:
```php
$options[
'preferred-converters' => ['vips', 'ewww'];
];
```
### Removing converters from the stack
To remove converters, you can use the `skip` option and prefixing. For example, to remove *cwebp* and *gd*:
```php
$options = [
'ewww-skip' => true,
'cwebp-skip' => true,
];
```
### Adding converters to the stack
If you are using a custom converter, you can add it to the stack like this:
```php
$options = [
'extra-converters' => [
'\\MyNameSpace\\WonderConverter'
],
];
```
It will be added to the bottom of the stack. To place it differently, use the `preferred-converters` option and set it to ie `'preferred-converters' => ['vips','\\MyNameSpace\\WonderConverter']`
Here is an example which adds an extra ewww converter. This way you can have a backup api-key in case the quota of the first has been exceeded.
```
$options = [
'extra-converters' => [
[
'converter' => 'ewww',
'options' => [
'api-key' => 'provide-backup-key-here',
]
]
]
];
```
Note however that you will not be able to reorder that new ewww converter using `preferred-converters`, as there are now two converters with id=ewww, and that option has not been designed for that. Instead, you can add a sub-stack of ewww converters - see the "Stacking" section below.
### Setting the converter array explicitly
Using the `converters` option, you can set the converter array explicitly. What differentiates this from the `preferred-converters` option (besides that it completely redefines the converter ordering) is that it allows you to set both the converters *and* options for each converter in one go and that it allows a complex structure - such as a stack within a stack. Also, this structure can simplify things in some cases, such as when the options is generated by a GUI, as it is in WebP Express.
The array specifies the converters to try and their order. Each item can be:
- An id (ie "cwebp")
- A fully qualified class name (in case you have programmed your own custom converter)
- An array with two keys: "converter" and "options".
Example:
```php
$options = [
'quality' => 71,
'converters' => [
'cwebp',
[
'converter' => 'vips',
'options' => [
'quality' => 72
]
],
[
'converter' => 'ewww',
'options' => [
'quality' => 73
]
],
'wpc',
'imagemagick',
'\\MyNameSpace\\WonderConverter'
],
];
```
### Stacking
Stack converters behave just like regular converters. They ARE in fact "regular", as they extend the same base class as all converters. This means that you can have a stack within a stack. You can for example utilize this for supplying a backup api key for the ewww converter. Like this:
```php
$options = [
'ewww-skip' => true, // skip the default ewww converter (we use stack of ewww converters instead)
'extra-converters' => [
[
// stack of ewww converters
'converter' => 'stack',
'options' => [
'ewww-skip' => false, // do not skip ewww from here on
'converters' => [
[
'converter' => 'ewww',
'options' => [
'api-key' => 'provide-preferred-key-here',
]
],
[
'converter' => 'ewww',
'options' => [
'api-key' => 'provide-backup-key-here',
]
]
],
]
]
],
'preferred-converters' => ['cwebp', 'vips', 'stack'], // set our stack of ewww converters third in queue
];
```
Note that we set `ewww-skip` in order to disable the *ewww* converter which is part of the defaults. As options are inherited, we have to reset this option again. These steps are not necessary when using the `converters` option.
Also note that the options for modifying the converters (`converters`, `extra-converters`, `converter-options`) does not get passed down.
Also note that if you want to add two stacks with `extra-converters`, the `preferred-converters` option will not work, as there are two converters called "stack". One workaround is to add those two stacks to their own stack, so you have three levels. Or you can of course simply use the `converters` option to get complete control.
### Shuffling
The stack can be configured to shuffling, meaning that the the order will be random. This can for example be used to balance load between several wpc instances in a sub stack.
Shuffling is enabled with the `shuffle` option.
Here is an example of balancing load between several *wpc* instances:
```php
$options = [
'wpc-skip' => true, // skip the default wpc converter (we use stack of wpc converters instead)
'extra-converters' => [
[
// stack of wpc converters
'converter' => 'stack',
'options' => [
'wpc-skip' => false, // do not skip wpc from here on
'shuffle' => true,
'converters' => [
[
'converter' => 'wpc',
'options' => [
'api-key' => 'my-dog',
'api-url' => 'my-wpc.com/wpc.php',
'api-version' => 1,
'crypt-api-key-in-transfer' => true,
]
],
[
'converter' => 'wpc',
'options' => [
'api-key' => 'my-other-dog',
'api-url' => 'my-other-wpc.com/wpc.php',
'api-version' => 1,
'crypt-api-key-in-transfer' => true,
]
]
],
]
]
],
'preferred-converters' => ['cwebp', 'vips', 'stack'], // set our stack of wpc converters third in queue
];
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

View File

@@ -0,0 +1 @@
<?php die("Access denied");

View File

@@ -0,0 +1,218 @@
# Introduction to converting with WebPConvert
**NOTE: This document only applies to the upcoming 2.0 version**
The library is able to convert images to webp using a variety of methods (*gd*, *imagick*, *vips* etc.), which we call "converters". A converter is called like this:
```php
use WebPConvert\Convert\Converters\Gd;
Gd::convert($source, $destination, $options=[], $logger=null);
```
All converters comes with requirements. For example, the *Gd* converter requires that Gd is installed and compiled with webp support. The cloud converters requires an api key. In case the conversion fails, an exception is thrown.
## Insights to the process
If *$logger* is supplied, the converter will log the details of how the conversion process went to that logger. You can for example use the supplied *EchoLogger* to print directly to screen or the *BufferLogger* to collect the log entries. Here is a simple example which prints the process to screen:
```php
use WebPConvert\Convert\Converters\Gd;
use WebPConvert\Loggers\EchoLogger;
Gd::convert($source, $destination, $options=[], new EchoLogger());
```
It will output something like this:
```text
GD Version: 2.2.5
image is true color
Quality set to same as source: 61
Converted image in 20 ms, reducing file size with 34% (went from 12 kb to 8 kb)
```
## The stack converter
When your software is going to be installed on a variety of systems which you do not control, you can try the converters one at the time until success. The converters has been designed to exit quickly when system requirements are not met. To make this task easy, a *Stack* converter has been created.
The stack converter has two special options:
| option | description |
| ------------------------- | ----------- |
| converters (array) | Converters to try (ids or class names, in case you have your own custom converter) |
| converter-options (array) | Extra options for specific converters. |
Alternatively to the converter-options array, you can simply prefix options with the converter id.
I recommend leave the converters array at the default unless you have strong reasons not to. Otherwise you might miss out when new converters are added.
### Example:
```php
<?php
use WebPConvert\Convert\Converters\Stack;
Stack::convert($source, $destination, $options = [
// PS: only set converters if you have strong reasons to do so
'converters' => [
'cwebp', 'vips', 'imagick', 'gmagick', 'imagemagick', 'graphicsmagick', 'wpc', 'ewww', 'gd'
],
// Any available options can be set here, they dribble down to all converters.
'metadata' => 'all',
// To override for specific converter, you can prefix with converter id:
'cwebp-metadata' => 'exif',
// This can for example be used for setting ewww api key:
'ewww-api-key' => 'your-ewww-api-key-here',
// As an alternative to prefixing, you can use "converter-options" to set a whole bunch of overrides in one go:
'converter-options' => [
'wpc' => [
'crypt-api-key-in-transfer' => true
'api-key' => 'my dog is white',
'api-url' => 'https://example.com/wpc.php',
'api-version' => 1,
],
],
], $logger=null);
```
Note: As an alternative to setting the third party credentials in the options, you can set them through constants or environment variables ("WEBPCONVERT_EWWW_API_KEY", "WEBPCONVERT_WPC_API_KEY", "WEBPCONVERT_WPC_API_URL"). Paths to binaries can also be set like that (it is rarely needed to do this): "WEBPCONVERT_CWEBP_PATH", "WEBPCONVERT_GRAPHICSMAGICK_PATH" and WEBPCONVERT_IMAGEMAGICK_PATH"
To set an environment variable in Apache, you can add a line like this in your `.htaccess` or vhost configuration:
```
# Set ewww api key for WebP Convert
SetEnv WEBPCONVERT_EWWW_API_KEY yourVerySecretApiKeyGoesHere
# Set custom path to imagick for WebP Convert
SetEnv WEBPCONVERT_IMAGEMAGICK_PATH /usr/local/bin/magick
```
To set a constant:
```php
define('WEBPCONVERT_IMAGEMAGICK_PATH', '/usr/local/bin/magick');
```
## Configuring the options
### Auto quality
**Q:** What do you get if you convert a low quality jpeg (ie q=50) into a high quality webp (ie q=90) ?\
**A:** You maintain the low quality, but you get a large file`
What should we have done instead? We should have converted with a quality around 50. Of course, quality is still low - we cannot fix that - but it will not be less, *and the converted file will be much smaller*.
As unnecessary large conversions are rarely desirable, this library per default converts jpeg files with the same quality level as the source. This functionality requires that either *imagemagick*, *graphicsmagick* or *imagick* is installed (not necessarily compiled with webp support). When they are, all converters will have the "auto" quality functionality. The *wpc* cloud converter supports auto quality if these are installed on the server that *wpc* is installed on.
How much can be gained? A lot!
The following low quality (q=50) jpeg weighs 54 kb. If this is converted to webp with quality=80, the size of the converted file is 52kb - almost no reduction! With auto, the quality of the webp will be set to 50, and the size will be 34kb. Visually, the results are indistinguable.
![A low quality jpeg](https://raw.githubusercontent.com/rosell-dk/webp-convert/master/docs/v2.0/converting/architecture-q50-w600.jpg)
**Q:** What do you get if you convert an excessively high quality jpeg into an excessively high quality webp?\
**A:** An excessively big file
The size of a webp file grows enormously with the quality setting. For the web however, a quality above 80 is rarely needed. For this reason the library has a per default limits the quality to the value of the *max-quality* option (default: 85).
In case quality detection is unavailable, the quality gets the value of the *default-quality* option (default is 70 for JPEGs and 85 for PNGs).
So, how much can be gained? A lot!
The following excessively high quality jpeg (q=100) weighs 146 kb. Converting it to webp with q=100 results in a 99kb image (this would happen if we had the auto feature, but not the max-quality feature). Converting it to q=85 results in a 40kb image.
![A (too) high quality jpeg](https://raw.githubusercontent.com/rosell-dk/webp-convert/master/docs/v2.0/converting/mouse-q100.jpg)
### Auto selecting between lossless/lossy encoding
WebP files can be encoded using either *lossless* or *lossy* encoding. The JPEG format is lossy and the PNG is lossless. However, this does not mean that you necessarily get the best conversion by always encoding JPEG to lossy and PNG to lossless. With JPEGs it is often the case, as they are usually pictures and pictures usually best encoded as lossy. With PNG it is however a different story, as you often can get a better compression using lossy encoding, also when using high quality level of say 85, which should be enough for the web.
As unnecessary large conversions are rarely desirable, this library per default tries to convert images using both lossy and lossless encoding and automatically selects the smallest. This is controlled using the *encoding* option, which per default is "auto", but can also be set to "lossy" or "lossless".
As an example, the following PNG (231 kb) will be compressed to 156 kb when converting to *lossless* webp. But when converting to *lossy* (quality: 85), it is compressed to merely 68 kb - less than half. (in case you are confused about the combination of lossy and transparency: Yes, you can have both at the same time with webp).
![Dice](https://raw.githubusercontent.com/rosell-dk/webp-convert/master/docs/v2.0/converting/dice.png)
Unless you changed the `near-lossless` option described below, the choice is actually between lossy and *near-lossless*.
Note that *gd* and *ewww* doesn't support this feature. *gd* can only produce lossy, and will simply do that. *ewww* can not be configured to use a certain encoding, but automatically chooses *lossless* encoding for PNGs and lossy for JPEGs.
### Near-lossless
*cwebp* and *vips* supports "near-lossless" mode. Near lossless produces a webp with lossless encoding but adjusts pixel values to help compressibility. The result is a smaller file. The price is described as a minimal impact on the visual quality.
As unnecessary large conversions are rarely desirable, this library per default sets *near-lossless* to 60. To disable near-lossless, set it to 100.
When compressing the image above (231 kb) to lossless, it compressed to 156 kb when near-lossless is set to 100. Setting near-lossless to 60 gets the size down to 110 kb while still looking great.
You can read more about the near-lossless mode [here](https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/0GmxDmlexek)
### Alpha-quality
All converters, except *gd* and *ewww* supports "alpha-quality" option. This allows lossy compressing of the alpha channel.
As unnecessary large conversions are rarely desirable, this library per default sets *alpha-quality* to 85. Set it to 100 to achieve lossless compression of alhpa.
Btw, the image above gets compressed to 68 kb with alpha quality set to 100. Surprisingly, it gets slightly larger (70 kb) with alpha quality set to 85. Setting alpha quality to 50 gets it down to merely 35 kb - about half - while still looking great.
You can read more about the alpha-quality option [here](https://developers.google.com/speed/webp/docs/cwebp)
### PNG og JPEG-specific options.
To have options depending on the image type of the source, you can use the `png` and `jpeg` keys.
The following options mimics the default behaviour:
```php
$options = [
'png' => [
'encoding' => 'auto', /* Try both lossy and lossless and pick smallest */
'near-lossless' => 60, /* The level of near-lossless image preprocessing (when trying lossless) */
'quality' => 85, /* Quality when trying lossy. It is set high because pngs is often selected to ensure high quality */
],
'jpeg' => [
'encoding' => 'auto', /* If you are worried about the longer conversion time, you could set it to "lossy" instead (lossy will often be smaller than lossless for jpegs) */
'quality' => 'auto', /* Set to same as jpeg (requires imagick or gmagick extension, not necessarily compiled with webp) */
'max-quality' => 80, /* Only relevant if quality is set to "auto" */
'default-quality' => 75, /* Fallback quality if quality detection isnt working */
]
];
```
You can use it for any option, also the converter specific options.
A use case could for example be to use different converters for png and jpeg:
```php
$options = [
'png' => [
'converters' => ['ewww'],
],
'jpeg' => [
'converters' => ['gd'],
]
];
```
## Available options
**All** available options are documented [here](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md).
Here is a quick overview of the few ones discussed here.
| Option | Default (jpeg) | Default (png) | Description |
| ----------------- | ------------------ | ------------------- | ---------------------------------------------------------------------------------- |
| quality | "auto" | 85 | See the "Auto quality" section above. |
| max-quality | 85 | 85 | Only relevant for jpegs and when quality is set to "auto". |
| default-quality | 75 | 85 | |
| metadata | "none" | "none" | Valid values: "all", "none", "exif", "icc", "xmp".<br><br>Note: Currently only *cwebp* supports all values. *gd* will always remove all metadata. *ewww*, *imagick* and *gmagick* can either strip all, or keep all (they will keep all, unless metadata is set to *none*) |
| encoding | "auto" | "auto" | See the "Auto selecting between lossless/lossy encoding" section above |
| jpeg | - | - | Array of options which will be merged into the other options when source is a JPEG |
| png | - | - | Array of options which will be merged into the other options when source is a PNG |
| skip | false | false | If true, conversion will be skipped (ie for skipping png conversion for some converters) |
## More info
- The complete api is available [here](https://www.bitwise-it.dk/webp-convert/api/2.0/html/index.xhtml)
- The converters are described in more detail here (for 1.3.9): [docs/v1.3/converting/converters.md](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/converting/converters.md).
- On the github wiki you can find installation instructions for imagick with webp, gd with webp, etc.
- This document is a newly written introduction to the convert api, which has been created as part of the 2.0 release. The old introduction, which was made for 1.3 is available here: [docs/converting/v1.3/convert.md](https://github.com/rosell-dk/webp-convert/blob/master/docs/v1.3/converting/convert.md).

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

View File

@@ -0,0 +1,346 @@
# Options
This is a list of all options available for converting.
Note that as the *stack* and *wpc* converters delegates the options to their containing converters, the options that they supports depend upon the converters they have been configured to use (and which of them that are operational)<br><br>
### `alpha-quality`
```
Type: integer (0-100)
Default: 85
Supported by: cwebp, vips, imagick, gmagick, imagemagick and graphicsmagick
```
Quality of alpha channel. Only relevant for lossy encoding and only relevant for images with alpha channel.<br><br>
### `auto-filter`
```
Type: boolean
Default: false
Supported by: cwebp, vips, imagick, gmagick and imagemagick
```
Turns auto-filter on. This algorithm will spend additional time optimizing the filtering strength to reach a well-balanced quality. Unfortunately, it is extremely expensive in terms of computation. It takes about 5-10 times longer to do a conversion. A 1MB picture which perhaps typically takes about 2 seconds to convert, will takes about 15 seconds to convert with auto-filter. So in most cases, you will want to leave this at its default, which is off.<br><br>
### `cwebp-command-line-options`
```
Type: string
Default: ''
Supported by: cwebp
```
This allows you to set any parameter available for cwebp in the same way as you would do when executing *cwebp*. You could ie set it to "-sharpness 5 -mt -crop 10 10 40 40". Read more about all the available parameters in [the docs](https://developers.google.com/speed/webp/docs/cwebp).<br><br>
### `cwebp-rel-path-to-precompiled-binaries`
```
Type: string
Default: './Binaries'
Supported by: cwebp
```
Allows you to change where to look for the precompiled binaries. While this may look as a risk, it is completely safe, as the binaries are hash-checked before being executed. The option is needed when you are using two-file version of webp-on-demand.
### `cwebp-try-common-system-paths`
```
Type: boolean
Default: true
Supported by: cwebp
```
If set, the converter will try to look for cwebp in locations such as `/usr/bin/cwebp`. It is a limited list. It might find something that isn't found using `try-discovering-cwebp` if these common paths are not within PATH or neither `which` or `whereis` are available.
### `cwebp-try-cwebp`
```
Type: boolean
Default: true
Supported by: cwebp
```
If set, the converter will try the a plain "cwebp" command (without specifying a path).
### `try-discovering-cwebp`
```
Type: boolean
Default: true
Supported by: cwebp
```
If set, the converter will try to discover installed cwebp binaries using the `which -a cwebp` command, or in case that fails, the `whereis -b cwebp` command. These commands will find cwebp binaries residing in PATH. They might find cwebp binaries which are not found by enabling `cwebp-try-common-system-paths`
### `cwebp-try-supplied-binary-for-os`
```
Type: boolean
Default: true
Supported by: cwebp
```
If set, the converter will try the precompiled cwebp binary that are located in `src/Convert/Converters/Binaries`, for the current OS. The binaries are hash-checked before executed.
### `default-quality`
```
Type: integer (0-100)
Default: 75 for jpegs and 85 for pngs
Supported by: all (cwebp, ewww, gd, ffmpeg, gmagick, graphicsmagick, imagick, imagemagick, vips)
```
Read about this option in the ["auto quality" section in the introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#auto-quality).<br><br>
### `encoding`
```
Type: string ("lossy" | "lossless" | "auto")
Default: "auto"
Supported by: cwebp, vips, ffmpeg, imagick, gmagick, imagemagick and graphicsmagick (gd always uses lossy encoding, ewww uses lossless for pngs and lossy for jpegs)
```
Read about this option in the ["lossy/lossless" section in the introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#auto-selecting-between-losslesslossy-encoding).<br><br>
### `ewww-api-key`
```
Type: string
Default: ''
Supported by: ewww
```
Api key for the ewww converter. The option is actually called *api-key*, however, any option can be prefixed with a converter id to only apply to that converter. As this option is only for the ewww converter, it is natural to use the "ewww-" prefix.
Note: This option can alternatively be set through the *EWWW_API_KEY* environment variable.<br><br>
### `ewww-check-key-status-before-converting`
```
Type: boolean
Default: true
Supported by: ewww
```
Decides whether or not the ewww service should be invoked in order to check if the api key is valid. Doing this for every conversion is not optimal. However, it would be worse if the service was contacted repeatedly to do conversions with an invalid api key - as conversion requests carries a big upload with them. As this library cannot prevent such repeated failures (it is stateless), it per default does the additional check. However, your application can prevent it from happening by picking up invalid / exceeded api keys discovered during conversion. Such failures are stored in `Ewww::$nonFunctionalApiKeysDiscoveredDuringConversion` (this is also set even though a converter later in the stack succeeds. Do not only read this value off in a catch clauses).
You should only set this option to *false* if you handle when the converter discovers invalid api keys during conversion.
### `jpeg`
```
Type: array
Default: []
Supported by: all
```
Override selected options when the source is a jpeg. The options provided here are simply merged into the other options when the source is a jpeg.
Read about this option in the [introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#png-og-jpeg-specific-options).<br><br>
### `log-call-arguments`
```
Type: boolean
Default: false
Supported by: all
```
Enabling this simply puts some more in the log - namely the arguments that was supplied to the call. Sensitive information is starred out.
### `low-memory`
```
Type: boolean
Default: false
Supported by: cwebp, imagick, imagemagick and graphicsmagick
```
Reduce memory usage of lossy encoding at the cost of ~30% longer encoding time and marginally larger output size. Read more in [the docs](https://developers.google.com/speed/webp/docs/cwebp).<br><br>
### `max-quality`
```
Type: integer (0-100)
Default: 85
Supported by: all (cwebp, ewww, ffmpeg, gd, gmagick, graphicsmagick, imagick, imagemagick, vips)
```
Read about this option in the ["auto quality" section in the introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#auto-quality).<br><br>
### `metadata`
```
Type: string ("all" | "none" | "exif" | "icc" | "xmp")
Default: 'none'
Supported by: 'none' is supported by all. 'all' is supported by all, except *gd* and *ffmpeg*. The rest is only supported by *cwebp*
```
Only *cwebp* supports all values. *gd* will always remove all metadata. The rest can either strip all or keep all (they will keep all, unless the option is set to *none*).<br><br>
### `method`
```
Type: integer (0-6)
Default: 6
Supported by: cwebp, vips, imagick, gmagick, imagemagick, graphicsmagick and ffmpeg
```
This parameter controls the trade off between encoding speed and the compressed file size and quality. Possible values range from 0 to 6. 0 is fastest. 6 results in best quality. PS: "method" is not a very descriptive name, but this is what its called in libwebp, which is why we also choose it for webpconvert. In ffmpeg, they renamed it "compression_level", in vips, they call it "reduction_effort". Both better names, but as said, use "method" with webpconvert<br><br>
### `near-lossless`
```
Type: integer (0-100)
Default: 60
Supported by: cwebp, vips
```
Specify the level of near-lossless image preprocessing. This option adjusts pixel values to help compressibility, but has minimal impact on the visual quality. It triggers lossless compression mode automatically. The range is 0 (maximum preprocessing) to 100 (no preprocessing). The typical value is around 60. Read more [here](https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/0GmxDmlexek).<br><br>
### `png`
```
Type: array
Default: []
Supported by: all
```
Override selected options when the source is a png. The options provided here are simply merged into the other options when the source is a png.
Read about this option in the [introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#png-og-jpeg-specific-options).<br><br>
### `preset`
```
Type: string ('none', 'default', 'photo', 'picture', 'drawing', 'icon' or 'text')
Default: "none"
Supported by: cwebp, vips, ffmpeg
```
Using a preset will set many of the other options to suit a particular type of source material. It even overrides them. It does however not override the quality option. "none" means that no preset will be set<br><br>
### `quality`
```
Type: integer (0-100) | "auto"
Default: "auto" for jpegs and 85 for pngs
Supported by: all (cwebp, ewww, gd, gmagick, graphicsmagick, imagick, imagemagick, vips, ffmpeg)
```
Quality for lossy encoding. Read about the "auto" option in the [introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#auto-quality).<br><br>
### `size-in-percentage`
```
Type: integer (0-100) | null
Default: null
Supported by: cwebp
```
This option sets the file size, *cwebp* should aim for, in percentage of the original. If you for example set it to *45*, and the source file is 100 kb, *cwebp* will try to create a file with size 45 kb (we use the `-size` option). This is an excellent alternative to the "quality:auto" option. If the quality detection isn't working on your system (and you do not have the rights to install imagick or gmagick), you should consider using this options instead. *Cwebp* is generally able to create webp files with the same quality at about 45% the size. So *45* would be a good choice. The option overrides the quality option. And note that it slows down the conversion - it takes about 2.5 times longer to do a conversion this way, than when quality is specified. Default is *off* (null).<br><br>
### `skip`
```
Type: boolean
Default: false
Supported by: all
```
Simply skips conversion. For example this can be used to skip png conversion for a specific converter like this:
```php
$options = [
'png' => [
'gd-skip' => true,
]
];
```
Or it can be used to skip unwanted converters from the default stack, like this:
```php
$options = [
'ewww-skip' => true,
'wpc-skip' => true,
'gd-skip' => true,
'imagick-skip' => true,
'gmagick-skip' => true,
];
```
<br>
### `stack-converters`
```
Type: array
Default: ['cwebp', 'vips', 'imagick', 'gmagick', 'imagemagick', 'graphicsmagick', 'wpc', 'ewww', 'gd']
Supported by: stack
```
Specify the converters to try and their order.
Beware that if you use this option, you will miss out when more converters are added in future updates. If the purpose of setting this option is to remove converters that you do not want to use, you can use the *skip* option instead. Ie, to skip ewww, set *ewww-skip* to true. On the other hand, if what you actually want is to change the order, you can use the *stack-preferred-converters* option, ie setting *stack-preferred-converters* to `['vips', 'wpc']` will move vips and wpc in front of the others. Should they start to fail, you will still have the others as backup.
The array specifies the converters to try and their order. Each item can be:
- An id (ie "cwebp")
- A fully qualified class name (in case you have programmed your own custom converter)
- An array with two keys: "converter" and "options".
`
Alternatively, converter options can be set using the *converter-options* option.
Read more about the stack converter in the [introduction](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#the-stack-converter).<br><br>
### `stack-converter-options`
```
Type: array
Default: []
Supported by: stack
```
Extra options for specific converters. Example:
```php
$options = [
'converter-options' => [
'vips' => [
'quality' => 72
],
]
]
```
<br>
### `stack-extra-converters`
```
Type: array
Default: []
Supported by: stack
```
Add extra converters to the bottom of the stack. The items are similar to those in the `stack-converters` option.<br><br>
### `stack-preferred-converters`
```
Type: array
Default: []
Supported by: stack
```
With this option you can move specified converters to the top of the stack. The converters are specified by id. For example, setting this option to ['vips', 'wpc'] ensures that *vips* will be tried first and - in case that fails - *wpc* will be tried. The rest of the converters keeps their relative order.<br><br>
### `stack-shuffle`
```
Type: boolean
Default: false
Supported by: stack
```
Shuffle the converters in the stack. This can for example be used to balance load between several wpc instances in a substack, as illustrated [here](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/converters/stack.md)<br><br>
### `use-nice`
```
Type: boolean
Default: false
Supported by: cwebp, graphicsmagick, imagemagick, ffmpeg
```
This option only applies to converters which are using exec() to execute a binary directly on the host. If *use-nice* is set, it will be examined if the [`nice`]( https://en.wikipedia.org/wiki/Nice_(Unix)) command is available on the host. If it is, the binary is executed using *nice*. This assigns low priority to the process and will save system resources - but result in slower conversion.<br><br>
### `vips-smart-subsample`
```
Type: boolean
Default: false
Supported by: vips
```
This feature seems not to be part of *libwebp* but intrinsic to vips. According to the [vips docs](https://jcupitt.github.io/libvips/API/current/VipsForeignSave.html#vips-webpsave), it enables high quality chroma subsampling.<br><br>
### `wpc-api-key`
```
Type: string
Default: ''
Supported by: wpc
```
Api key for the wpc converter. The option is actually called *api-key*, however, any option can be prefixed with a converter id to only apply to that converter. As this option is only for the wpc converter, it is natural to use the "wpc-" prefix. Same goes for the other "wpc-" options.
Note: You can alternatively set the api key through the *WPC_API_KEY* environment variable.<br><br>
### `wpc-api-url`
```
Type: string
Default: ''
Supported by: wpc
```
Note: You can alternatively set the api url through the *WPC_API_URL* environment variable.<br><br>
### `wpc-api-version`
```
Type: integer (0 - 1)
Default: 0
Supported by: wpc
```
<br>
### `wpc-crypt-api-key-in-transfer`
```
Type: boolean
Default: false
Supported by: wpc
```
<br>
### `wpc-secret`
```
Type: string
Default: ''
Supported by: wpc
```
Note: This option is only relevant for api version 0.

View File

@@ -0,0 +1 @@
<?php die("Access denied");

View File

@@ -0,0 +1,73 @@
convert# Migrating to 2.0
## Converting
### Changes in conversion api
While the code have been refactored quite extensively, if you have stuck to `WebPConvert::convert()` and/or `WebPConvert::convertAndServe()`, there is only a few things you need to know.
First and foremost: *`WebPConvert::convert` no longer returns a boolean indicating the result*. So, if conversion fails, an exception is thrown, no matter what the reason is. When migrating, you will probably need to remove some lines of code where you test the result.
Also, a few options has been renamed and a few option defaults has been changed.
#### The options that has been renamed are the following:
- Two converters have changed IDs and class names: The ids that are changed are: *imagickbinary* => *imagemagick* and *gmagickbinary* => *graphicsmagick*
- In *ewww*, the `key` option has been renamed to `api-key` (or [`ewww-api-key`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#ewww-api-key))
- In *wpc*, the `url` option has been renamed to `api-url` (or [`wpc-api-url`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#wpc-api-url))
* In *cwebp*, the [`lossless`] option is now replaced with the new `encoding` option (which is not boolean, but "lossy", "lossless" or ["auto"](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md#auto-selecting-between-losslesslossy-encoding))
* In *cwebp*, the [`autofilter`] option has been renamed to "auto-filter"
- In *gd*, the `skip-pngs` option has been removed and replaced with the general `skip` option and prefixing. So `gd-skip` amounts to the same thing, but notice that Gd no longer skips per default.
#### The option defaults that has been changed are the following:
- the `converters` default now includes the cloud converters (*ewww* and *wpc*) and also two new converters, *vips* and *graphicsmagick*. So it is not necessary to add *ewww* or *wpc* explicitly. Also, when you set options with `converter-options` and point to a converter that isn't in the stack, in 1.3.9, this resulted in the converter automatically being added. This behavior has been removed.
- *gd* no longer skips pngs per default. To make it skip pngs, set `gd-skip` to *true*
- Default quality is now 75 for jpegs and 85 for pngs (it was 75 for both)
- For *cwebp*, the `lossless` has been removed. Use the new `encoding` option instead.
- For *wpc*, default `secret` and `api-key` are now "" (they were "my dog is white")
### New convert options
You might also be interested in the new options available in 2.0:
- Added a syntax for conveniently targeting specific converters. If you for example prefix the "quality" option with "gd-", it will override the "quality" option, but only for gd.
- Certain options can now be set with environment variables too ("EWWW_API_KEY", "WPC_API_KEY" and "WPC_API_URL")
- Added new *vips* converter.
- Added new *graphicsmagick* converter.
- Added new *stack* converter (the stack functionality has been moved into a converter)
- Added [`jpeg`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#jpeg) and [`png`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#png) options
- Added [`alpha-quality`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#alpha-quality) option for *cwebp*, *vips*, *imagick*, *imagemagick* and *graphicsmagick*.
- Added [`auto-filter`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#autofilter) option for *cwebp*, *imagick*, *imagemagick* and the new *vips* converter.
- Added [`encoding`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#encoding) option (lossy | lossless | auto). lossless and auto is supported for *cwebp*, *imagick*, *imagemagick*, *graphicsmagick* and the new *vips* converter.
- Added [`near-lossless`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#near-lossless) option for *cwebp* and *imagemagick*.
- Added [`preset`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#preset) option for *cwebp* and the new *vips* converter.
- Added [`skip`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#skip) option (its general and works for all converters)
- Besides the ones mentioned above, *imagemagick* now also supports [`low-memory`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#low-memory), [`metadata`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#metadata) ("all" or "none") and [`method`](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/options.md#method). *imagemagick* has become very potent!
## Serving
The classes for serving has also been refactored quite extensively, but again, if you have stuck to `WebPConvert::convertAndServe`, there is only a few things you need to know.
First and foremost, *`WebPConvert::convertAndServe` has been renamed to `WebPConvert::serveConverted()`*. The reason for this change is that it more accurately describes what is happening: A converted file is served. The old name implied that a conversion was always going on, which is not the case (if the file at destination already exists, which is not bigger or older than the source, that file is served directly).
Besides this, there is the following changes in options:
- A new option `convert` has been created for supplying the conversion options. So the conversion options are no longer "mingled" with the serving options, but has its own option.
- Options regarding serving the image are now organized into its own `serve-image` setting, which again has been reorganized.
- A new option `serve-image > headers > cache-control` controls whether to set cache control header (default: false).
- The `fail` option no longer support the "report-as-image" value. It however supports a new value: "throw".
- The `fail-when-original-unavailable` option has been renamed to `fail-when-fail-fails`. In 2.0, the original not being available is no longer the only thing that can cause the fail action to fail &ndash; the library now checks the mime type of the source file and only serves it if it is either png or jpeg.
- The `error-reporting` option has been removed. The reason for it being removed is that it is considered bad practice for a library to mess with error handling. However, *this pushes the responsibility to you*. You should make sure that no warnings ends up in the output, as this will corrupt the image being served. You can for example ensure that by calling `ini_set('display_errors', '0');` or `error_reporting(0);` (or both), or by creating your own error handler.
- The `aboutToServeImageCallBack` option has been removed. You can instead extend the `ServeConvertedWebP` class and override `serveOriginal` and `serveDestination`. You can call the serve method of your extended class, but then you will not have the error handling (the `fail` and `fail-if-fail-fails` options). Too add this, you can call `ServeConvertedWebPWithErrorHandling::serve` and make sure to override the default of the last argument.
- The `aboutToPerformFailAction` option has been removed. You can instead set `fail` to `throw` and handle the exception in a *catch* clause. Or you can extend the `ServeConvertedWebPWithErrorHandling` class and override the `performFailAction` method.
- The `add-x-header-status` and `add-x-header-options` options have been removed.
- The `require-for-conversion` option has been removed. You must either use with composer or create a simple autoloader (see next section)
## WebP On demand
If you are using the "non-composer" version of webp demand (the one where you only upload two files - `webp-on-demand-1.inc` and `webp-on-demand-2.inc`), you were probably using the `require-for-conversion` option. This option is no longer supported. But you never really needed it in the first place, because the you create and register an autoloader instead:
```php
function autoloader($class) {
if (strpos($class, 'WebPConvert\\') === 0) {
require_once __DIR__ . '/webp-on-demand-2.inc';
}
}
spl_autoload_register('autoloader', true, true);
```

View File

@@ -0,0 +1 @@
<?php die("Access denied");

View File

@@ -0,0 +1,157 @@
# Introduction to serving converted WebP files with WebPConvert
**NOTE: This document only applies to the upcoming 2.0 version**
The classes for serving first and foremost helps you handle the cached files intelligently (not serving them if they are larger or older than the original). It also provides a convenient way to deal with conversion failures and setting headers.
In the following example, all available *serve* options are explicitly set to their default values.
```php
use WebPConvert\WebPConvert;
WebPConvert::serveConverted($source, $destination, [
// failure handling
'fail' => 'original', // ('original' | 404' | 'throw' | 'report')
'fail-when-fail-fails' => 'throw', // ('original' | 404' | 'throw' | 'report')
// options influencing the decision process of what to be served
'reconvert' => false, // if true, existing (cached) image will be discarded
'serve-original' => false, // if true, the original image will be served rather than the converted
'show-report' => false, // if true, a report will be output rather than the raw image
// warning handling
'suppress-warnings' => true, // if you set to false, make sure that warnings are not echoed out!
// options when serving an image (be it the webp or the original, if the original is smaller than the webp)
'serve-image' => [
'headers' => [
'cache-control' => true,
'content-length' => true,
'content-type' => true,
'expires' => false,
'last-modified' => true,
'vary-accept' => false
],
'cache-control-header' => 'public, max-age=31536000',
],
// redirect tweak
'redirect-to-self-instead-of-serving' => false, // if true, a redirect will be issues rather than serving
'convert' => [
// options for converting goes here
'quality' => 'auto',
]
]);
```
## Failure handling
The `fail` option gives you an easy way to handle errors. Setting it to 'original' tells it to handle errors by serving the original file instead (*$source*). This could be a good choice on production servers. On development servers, 'throw' might be a good option. It simply rethrows the exception that was thrown by *WebPConvert::convert()*. '404' could also be an option, but it has the weakness that it will probably only be discovered by real persons seeing a missing image.
The fail action might fail too. For example, if it is set to 'original' and the failure is that the original file doesn't exist. Or, more delicately, it may have a wrong mime type - our serve method will not let itself be tricked into serving *exe* files as the 'original'. Anyway, you can control what to do when fail fails using the *fail-when-fail-fails* option. If that fails too, the original exception is thrown. The fun stops there, there is no "fail-when-fail-when-fail-fails" option to customize this.
The failure handling is implemented as an extra layer. You can bypass it by calling `WebPConvert\Serve\ServeConvertedWebP::serve()` directly. Doing that will give the same result as if you set `fail` to 'throw'.
## Options influencing the decision process
The default process is like this:
1. Is there a file at the destination? If not, trigger conversion
2. Is the destination older than the source? If yes, delete destination and trigger conversion
3. Serve the smallest file (destination or source)
You can influence the process with the following options:
*reconvert*
If you set *reconvert* to true, the destination and conversion is triggered (between step 1 and 2)
*serve-original*
If you set *serve-original* to true, process will take its cause from (1) to (2) and then end with source being served.
*show-report*
If you set `show-report`, the process is skipped entirely, and instead a report is generated of how a fresh conversion using the supplied options goes.
## Headers
Leaving errors and reports out of account for a moment, the *WebPConvert::serveConverted()* ultimately has two possible outcomes: Either a converted image is served or - if smaller - the source image. If the source is to be served, its mime type will be detected in order to make sure it is an image and to be able to set the content type header. Either way, the actual serving is passed to `Serve\ServeFile::serve`. The main purpose of this class is to add/set headers.
#### *Cache-Control* and *Expires* headers
Default behavior is to neither set the *Cache-Control* nor the *Expires* header. Once you are on production, you will probably want to turn these on. The default is btw one year (31536000 seconds). I recommend the following for production:
```
'serve-image' => [
'headers' => [
'cache-control' => true,
'expires' => false,
],
'cache-control-header' => 'public, max-age=31536000',
],
```
The value for the *Expires* header is calculated from "max-age" found in the *cache-control-header* option and the time of the request. The result is an absolute time, ie "Expires: Thu, 07 May 2020 07:02:37 GMT". As most browsers now supports the *Cache-Control* header, *from a performance perspective*, there is no need to also add the expires header. However, some tools complains if you don't (gtmetrix allegedly), and there is no harm in adding both headers. More on this discussion [[here]](https://github.com/rosell-dk/webp-convert/issues/126).
#### *Vary: Accept* header
This library can be used as part of a solution that serves webp files to browsers that supports it, while serving the original file to browsers that does not *on the same URL*. Such a solution typically inspects the *Accept* request header in order to determine if the client supports webp or not. Thus, the response will *vary* along with the "Accept" header and the world (and proxies) should be informed about this, so they don't end up serving cached webps to browsers that does not support it. To add the "Vary: Accept" header, simply set the *serve-image > headers > vary-accept* option to true.
#### *Last-Modified* header
The Last-Modified header is also used for caching purposes. You should leave that setting on, unless you set it by other means. You control it with the *serve-image > headers > last-modified* option.
#### *Content-Type* header
The *Content-Type* header tells browsers what they are receiving. This is important information and you should leave the *serve-image > headers > content-type* option at its default (true), unless you set it by other means.
When the outcome is to serve a webp, the header will be set to: "Content-Type: image/webp". When the original is to be served, the library will try to detect the mime type of the file and set the content type accordingly. The [image-mime-type-guesser](https://github.com/rosell-dk/image-mime-type-guesser) library is used for that.
#### *Content-Length* header
The *Content-Length* header tells browsers the length of the content. According to [the specs](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13), it should be set unless it is prohibited by rules in [section 4.4](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4). In that section we learn that it should not be set when the *Transfer-Encoding* header is set (which it often is, to "chunked"). However, no harm done, because it also says that clients should ignore the header in case *Transfer-Encoding* is set. From this I concluded that it makes sense to default the *serve-image > headers > content-length* to true. I might however change this in case I should learn that the header could be problematic in some way. So if you decided you want it, do not rely on the default, but set it to *true*. See discussion on this subject [here](https://stackoverflow.com/questions/3854842/content-length-header-with-head-requests/3854983#3854983).
#### *X-WebP-Convert-Log* headers
The serve method adds *X-WebP-Convert-Log* headers in order to let you know what went on.
For example, if there is no converted image and conversion was successful, the following headers will be sent:
```
X-WebP-Convert-Log: Converting (there were no file at destination)
X-WebP-Convert-Log: Serving converted file
```
On the next call (presuming the webp has not been deleted), no conversion is needed and you should simply see:
```
X-WebP-Convert-Log: Serving converted file
```
But say that the first conversion actually failed. In case you have permission problems, the output could be:
```
X-WebP-Convert-Log: Converting (there were no file at destination)
X-WebP-Convert-Log: Failed creating folder. Check the permissions!
X-WebP-Convert-Log: Performing fail action: original
```
In case the problem is that the conversion failed, you could see the following:
```
X-WebP-Convert-Log: Converting (there were no file at destination)
X-WebP-Convert-Log: None of the converters in the stack are operational
X-WebP-Convert-Log: Performing fail action: original
```
If you need more info about the conversion process in order to learn why the converters aren't working, enable the *show-report* option.
As a last example, say you have supplied a non-existing file as source and `fail` is set to "original" (which will also fail). Result:
```
X-WebP-Convert-Log: Source file was not found
X-WebP-Convert-Log: Performing fail action: original
X-WebP-Convert-Log: Performing fail action: throw
```
## The redirect tweak (will be available in 2.3.0)
There are cases where serving the image directly with PHP isn't optimal.
One case is WP Engine. Even though webp-convert adds a Vary:Accept header, the header is not present in the response on WP Engine. It is somehow overwritten by the caching machinery and set to Vary:Accept-Encoding, Cookie.
If however rules have been set up to redirect images directly to existing webps, one can overcome the problem by redirecting the image request back to itself rather than serving the webp directly.
You can achieve this by setting the *redirect-to-self-instead-of-serving* option to true.
Beware of risk of an endless redirect loop. Such loop will happen if the redirection to existing webp rules aren't set up correctly. To prevent this, it is recommended that you only set the option to true after checking that the destination file does not exist. But note that this check does not completely prevent such loops occurring when redirection to existing rules are missing - as the 302 redirect could get cached (it does that on WP Engine). So bottom line: Only use this feature when you have server rules set up for redirecting images to their corresponding webp images (for client that supports webp) - *and you are certain that these rules works*.
## More info
- The complete api is available [here](https://www.bitwise-it.dk/webp-convert/api/2.0/html/index.xhtml)

View File

@@ -0,0 +1,116 @@
# Serving WebP from a Laravel Nginx site
**NOTE: This document only applies to the upcoming 2.0 version**
This should work with most php sites although I'm basing the Nginx configuration around what's commonly seen with Laravel installations.
Create webp converter script in ```project_root/public/webp-on-demand.php```
```
<?php
require '../vendor/autoload.php';
use WebPConvert\WebPConvert;
$source = __DIR__ . $_GET['source'];
$destination = $source . '.webp';
WebPConvert::serveConverted($source, $destination, [
'fail' => 'original', // If failure, serve the original image (source). Other options include 'throw', '404' and 'report'
// 'show-report' => true, // Generates a report instead of serving an image
'serve-image' => [
'headers' => [
'cache-control' => true,
'vary-accept' => true,
// other headers can be toggled...
],
'cache-control-header' => 'max-age=2',
],
'convert' => [
// all convert option can be entered here (ie "quality")
],
]);
```
### Configure Nginx
We just need to add the following block to our site in ```/etc/sites-enabled/```
```
location ~* ^/.*\.(png|jpe?g)$ {
add_header Vary Accept;
expires 365d;
if ($http_accept !~* "webp"){
break;
}
try_files
$uri.webp
/webp-on-demand.php?source=$uri
;
}
```
Then reload Nginx ```sudo systemctl restart nginx```
The full Nginx block should look like
```
server {
server_name webp-testing.com;
root /home/forge/webp-testing.com/public;
index index.html index.htm index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~* ^/.*\.(png|jpe?g)$ {
add_header Vary Accept;
expires 365d;
if ($http_accept !~* "webp"){
break;
}
try_files
$uri.webp
/webp-on-demand.php?source=$uri
;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/webp-testing.com-error.log error;
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
# cache static assets
location ~* \.(gif|ico|css|pdf|svg)$ {
expires 365d;
}
location ~* \.(js)$ {
add_header Cache-Control no-cache;
}
}
```

View File

@@ -0,0 +1 @@
<?php die("Access denied");

View File

@@ -0,0 +1,181 @@
# Tweaks
## Store converted images in separate folder
In most cases, you probably want the cache of converted images to be stored in their own folder rather than have them mingled with the source files.
To have have the cache folder contain a file structure mirroring the structure of the original files, you can do this:
```php
$applicationRoot = $_SERVER["DOCUMENT_ROOT"]; // If your application is not in document root, you can change accordingly.
$imageRoot = $applicationRoot . '/webp-images'; // Change to where you want the webp images to be saved
$sourceRel = substr($source, strlen($applicationRoot));
$destination = $imageRoot . $sourceRel . '.webp';
```
If your images are stored outside document root (a rare case), you can simply use the complete absolute path:
```php
$destination = $imageRoot . $source . '.webp'; // pst: $source is an absolute path, and starts with '/'
```
This will ie store a converted image in */var/www/example.com/public_html/app/webp-images/var/www/example.com/images/logo.jpg.webp*
If your application can be configured to store outside document root, but rarely is, you can go for this structure:
```php
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageRoot = $contentDirAbs . '/webp-images';
if (substr($source, 0, strlen($docRoot)) === $docRoot) {
// Source file is residing inside document root.
// We can store relative to that.
$sourceRel = substr($source, strlen($docRoot));
$destination = $imageRoot . '/doc-root' . $sourceRel . '.webp';
} else {
// Source file is residing outside document root.
// we must add complete path to structure
$destination = $imageRoot . '/abs' . $source . '.webp';
}
```
If you do not know the application root beforehand, and thus do not know the appropriate root for the converted images, see next tweak.
## Get the application root automatically
When you want destination files to be put in their own folder, you need to know the root of the application (the folder in which the .htaccess rules resides). In most applications, you know the root. In many cases, it is simply the document root. However, if you are writing an extension, plugin or module to a framework that can be installed in a subfolder, you may have trouble finding it. Many applications have a *index.php* in the root, which can get it with `__DIR__`. However, you do not want to run an entire bootstrap each time you serve an image. Obviously, to get around this, you can place *webp-on-demand.php* in the webroot. However, some frameworks, such as Wordpress, will not allow a plugin to put a file in the root. Now, how could we determine the application root from a file inside some subdir? Here are three suggestions:
1. You could traverse parent folders until you find a file you expect to be in application root (ie a .htaccess containing the string "webp-on-demand.php"). This should work.
2. If the rules in the *.htaccess* file are generated by your application, you probably have access to the path at generation time. You can then simply put the path in the *.htaccess*, as an extra parameter to the script (or better: the relative path from document root to the application).
3. You can use the following hack:
### The hack
The idea is to grab the URL path of the image in the *.htaccess* and pass it to the script. Assuming that the URL paths always matches the file paths, we can get the application root by subtracting that relative path to source from the absolute path to source.
In *.htaccess*, we grab the url-path by appending "&url-path=$1.$2" to the rewrite rule:
```
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&url-path=$1.$2 [NC,L]
```
In the script, we can then calculate the application root like this:
```php
$applicationRoot = substr($_GET['source'], 0, -strlen($_GET['url-path']));
```
## CDN
To work properly with a CDN, a "Vary Accept" header should be added when serving images. This is a declaration that the response varies with the *Accept* header (recall that we inspect *Accept* header in the .htaccess to determine if the browsers supports webp images). If this header is missing, the CDN will see no reason to cache separate images depending on the Accept header.
Add this snippet to the *.htaccess* to make webp-on-demand work with CDN's:
```
<IfModule mod_headers.c>
SetEnvIf Request_URI "\.(jpe?g|png)" ADDVARY
# Declare that the response varies depending on the accept header.
# The purpose is to make CDN cache both original images and converted images.
Header append "Vary" "Accept" env=ADDVARY
</IfModule>
```
***Note:*** When configuring the CDN, you must make sure to set it up to forward the the "Accept" header to your origin server.
## Make .htaccess route directly to existing images
There may be a performance benefit of using the *.htaccess* file to route to already converted images, instead of letting the PHP script serve it. Note however:
- If you do the routing in .htaccess, the solution will not be able to discard converted images when original images are updated.
- Performance benefit may be insignificant (*WebPConvertAndServe* class is not autoloaded when serving existing images)
Add the following to the *.htaccess* to make it route to existing converted images. Place it above the # Redirect images to webp-on-demand.php" comment. Take care of replacing [[your-base-path]] with the directory your *.htaccess* lives in (relative to document root, and [[your-destination-root]] with the directory the converted images resides.
```
# Redirect to existing converted image (under appropriate circumstances)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/[[your-base-path]]/[[your-destination-root]]/$1.$2.webp -f
RewriteRule ^\/?(.*)\.(jpe?g|png)$ /[[your-base-path]]/[[your-destination-root]]/$1.$2.webp [NC,T=image/webp,L]
```
*edit:* Removed the QSD flag from the RewriteRule because it is not supported in Apache < 2.4 (and it [triggers error](https://github.com/rosell-dk/webp-express/issues/155))
Note however that DOCUMENT_ROOT can be unreliable.
If you store the webp images in the same folder as the originals and append ".webp" (rather than replace the file extension), you can do this instead:
```
# Redirect to existing converted image (under appropriate circumstances)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME}.webp -f
RewriteRule ^/?(.+)\.(jpe?g|png)$ $1.$2.webp [T=image/webp,L]
```
RewriteCond %{REQUEST_FILENAME}.webp -f
### Redirect with CDN support
If you are using a CDN, and want to redirect to existing images with the .htaccess, it is a good idea to add a "Vary Accept" header. This instructs the CDN that the response varies with the *Accept* header (we do not need to do that when routing to webp-on-demand.php, because the script takes care of adding this header, when appropriate.)
You can achieve redirect with CDN support with the following rules:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect to existing converted image (under appropriate circumstances)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/[[your-base-path]]/[[your-destination-root]]/$1.$2.webp -f
RewriteRule ^\/?(.*)\.(jpe?g|png)$ /[[your-base-path]]/[[your-destination-root]]/$1.$2.webp [NC,T=image/webp,QSD,E=WEBPACCEPT:1,L]
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&url-path=$1.$2 [NC,L]
</IfModule>
<IfModule mod_headers.c>
# Apache appends "REDIRECT_" in front of the environment variables, but LiteSpeed does not.
# These next line is for Apache, in order to set environment variables without "REDIRECT_"
SetEnvIf REDIRECT_WEBPACCEPT 1 WEBPACCEPT=1
# Make CDN caching possible.
# The effect is that the CDN will cache both the webp image and the jpeg/png image and return the proper
# image to the proper clients (for this to work, make sure to set up CDN to forward the "Accept" header)
Header append Vary Accept env=WEBPACCEPT
</IfModule>
AddType image/webp .webp
```
## Forward the querystring
By forwarding the query string, you can allow control directly from the URL. You could for example make it possible to add "?debug" to an image URL, and thereby getting a conversion report. Or make "?reconvert" force reconversion.
In order to forward the query string, you need to add this condition before the RewriteRule that redirects to *webp-on-demand.php*:
```
RewriteCond %{QUERY_STRING} (.*)
```
That condition will always be met. The side effect is that it stores the match (the complete querystring). That match will be available as %1 in the RewriteRule. So, in the RewriteRule, we will have to add "&%1" after the last argument. Here is a complete solution:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{QUERY_STRING} (.*)
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME}&%1 [NC,L]
</IfModule>
AddType image/webp .webp
```
Of course, in order to *do* something with that querystring, you must use them in your *webp-on-demand.php* script. You could for example use them directly in the options array sent to the *convertAndServe()* method. To achieve the mentioned "debug" and "reconvert" features, do this:
```php
$options = [
'show-report' => isset($_GET['debug']),
'reconvert' => isset($_GET['reconvert']),
'serve-original' => isset($_GET['original']),
];
```
*EDIT:*
I have just discovered a simpler way to achieve the querystring forward: The [QSA flag](https://httpd.apache.org/docs/trunk/rewrite/flags.html).
So, simply set the QSA flag in the RewriteRule, and nothing more:
```
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME} [NC,QSA,L]
```

View File

@@ -0,0 +1,145 @@
# WebP on demand
This is a solution for automatically serving WebP images instead of jpeg/pngs [for browsers that supports WebP](https://caniuse.com/#feat=webp) (At the time of writing, 78% of all mobile users and 72% of all desktop users uses browsers supporting webp)
Once set up, it will automatically convert images, no matter how they are referenced. It for example also works on images referenced in CSS. As the solution does not require any change in the HTML, it can easily be integrated into any website / framework
## Overview
A setup consists of a PHP script that serves converted images and some *redirect rules* that redirects JPG/PNG images to the script.
## Requirements
* *Apache* or *LiteSpeed* web server. Can be made to work with *NGINX* as well. Documentation is on the roadmap.
* *mod_rewrite* module for Apache
* PHP >= 5.6 (we are only testing down to 5.6. It should however work in 5.5 as well)
* That one of the *webp-convert* converters are working (these have different requirements)
## Installation
Here we assume you are using Composer. [Not using composer? - Follow me!](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/without-composer.md)
### 1. Require the webp-convert library with composer
```
composer require rosell-dk/webp-convert
```
### 2. Create the script
Create a file *webp-on-demand.php*, and place it in webroot, or where-ever you like in you web-application.
Here is a minimal example to get started with:
```php
<?php
// To start with, lets display any errors.
// - this will reveal if you entered wrong paths
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Once you got it working, make sure that PHP warnings are not send to the output
// - this will corrupt the image
// For example, you can do it by commenting out the lines below:
// error_reporting(0);
// ini_set("display_errors", 0);
require 'vendor/autoload.php'; // Make sure to point this correctly
use WebPConvert\WebPConvert;
$source = $_GET['source']; // Absolute file path to source file. Comes from the .htaccess
$destination = $source . '.webp'; // Store the converted images besides the original images (other options are available!)
$options = [
// UNCOMMENT NEXT LINE, WHEN YOU ARE UP AND RUNNING!
'show-report' => true // Show a conversion report instead of serving the converted image.
// More options available!
// https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md
// https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/serving/introduction-for-serving.md
];
WebPConvert::serveConverted($source, $destination, $options);
```
### 3. Add redirect rules
Place the following rewrite rules in a *.htaccess* file in the directory where you want the solution to take effect:
```
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect images to webp-on-demand.php (if browser supports webp)
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)\.(jpe?g|png)$ webp-on-demand.php?source=%{SCRIPT_FILENAME} [NC,L]
</IfModule>
AddType image/webp .webp
```
If you have placed *webp-on-demand.php* in a subfolder, you will need to change the rewrite rule accordingly.
The `RewriteCond %{REQUEST_FILENAME} -f` is not strictly necessary, but there to be sure that we got an existing file, and it could perhaps also prevent some undiscovered way of misuse.
### 4. Validate that it works
Browse to a JPEG image. Instead of an image, you should see a conversion report. Hopefully, you get a success. Otherwise, you need to hook up to a cloud converter or try to meet the requirements for cwebp, gd or imagick.
Once you get a successful conversion, you can uncomment the "show-report" option in the script.
It should work now, but to be absolute sure:
- Visit a page on your site with an image on it, using *Google Chrome*.
- Right-click the page and choose "Inspect"
- Click the "Network" tab
- Reload the page
- Find a jpeg or png image in the list. In the "type" column, it should say "webp". There should also be a *X-WebP-Convert-Status* header on the image that provides some insights on how things went.
### 5. Try this improvement and see if it works
It seems that it is not necessary to pass the filename in the query string.
Try replacing `$source = $_GET['source'];` in the script with the following:
```php
$docRoot = rtrim($_SERVER["DOCUMENT_ROOT"], '/');
$requestUriNoQS = explode('?', $_SERVER['REQUEST_URI'])[0];
$source = $docRoot . urldecode($requestUriNoQS);
```
And you can then remove `?source=%{SCRIPT_FILENAME}` from the `.htaccess` file.
There are some benefits of not passing in query string:
1. Passing a path in the query string may be blocked by a firewall, as it looks suspicious.
2. The script called to convert arbitrary files
3. One person experienced problems with spaces in filenames passed in the query string. See [this issue](https://github.com/rosell-dk/webp-convert/issues/95)
### 6. Customizing and tweaking
Basic customizing is done by setting options in the `$options` array. Check out the [docs on convert()](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/convert.md) and the [docs on convertAndServe()](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/serving/convert-and-serve.md)
Other tweaking is described in *docs/webp-on-demand/tweaks.md*:
- [Store converted images in separate folder](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/tweaks.md#store-converted-images-in-separate-folder)
- [CDN](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/tweaks.md#cdn)
- [Make .htaccess route directly to existing images](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/tweaks.md#make-htaccess-route-directly-to-existing-images)
- [Forward the query string](https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/webp-on-demand/tweaks.md#forward-the-querystring)
## Troubleshooting
### The redirect rule doesn't seem to be working
If images are neither routed to the converter or a 404, it means that the redirect rule isn't taking effect. Common reasons for this includes:
- Perhaps there are other rules in your *.htaccess* that interfere with the rules?
- Perhaps your site is on *Apache*, but it has been configured to use *Nginx* to serve image files. To find out which server that is handling the images, browse to an image and eximine the "Server" response header. In case *NGINX* are serving images, see if you can reconfigure your server setup. Alternatively, you can create *NGINX* rewrite rules. There are some [here](https://github.com/S1SYPHOS/kirby-webp#nginx) and [there](https://github.com/uhop/grunt-tight-sprite/wiki/Recipe:-serve-WebP-with-nginx-conditionally).
- Perhaps the server isn't configured to allow *.htaccess* files? Try inserting rubbish in the top of the *.htaccess* file and refresh. You should now see an *Internal Server Error* error page. If you don't, your *.htaccess* file is ignored. Probably you will need to set *AllowOverride All* in your Virtual Host. [Look here for more help](
https://docs.bolt.cm/3.4/howto/making-sure-htaccess-works#test-if-htaccess-is-working)
- Perhaps the Apache *mod_rewrite* extension isn't enabled? Try removing both `<IfModule mod_rewrite.c>` and `</IfModule>` lines: if you get an *Internal Server Error* error page after this change, it's probably that it's indeed not enabled.
## Related
* https://www.maxcdn.com/blog/how-to-reduce-image-size-with-webp-automagically/
* https://www.digitalocean.com/community/tutorials/how-to-create-and-serve-webp-images-to-speed-up-your-website

View File

@@ -0,0 +1,58 @@
# WebP On Demand without composer
For your convenience, the library has been cooked down to two files: *webp-on-demand-1.inc* and *webp-on-demand-2.inc*. The second one is loaded when the first one decides it needs to do a conversion (and not simply serve existing image).
## Installing
### 1. Copy the latest build files into your website
The build files are distributed [here](https://github.com/rosell-dk/webp-convert-concat/tree/master/build). Open the "latest" folder and copy *webp-on-demand-1.inc* and *webp-on-demand-2.inc* into your website. They can be located wherever you like.
### 2. Create a *webp-on-demand.php*
Create a file *webp-on-demand.php*, and place it in webroot, or where-ever you like in you web-application.
Here is a minimal example to get started with:
```php
<?php
// To start with, lets display any errors.
// - this will reveal if you entered wrong paths
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Once you got it working, make sure that PHP warnings are not send to the output
// - this will corrupt the image
// For example, you can do it by commenting out the lines below:
// error_reporting(0);
// ini_set("display_errors", 0);
use WebPConvert\WebPConvert;
require 'webp-on-demand-1.inc';
function webpconvert_autoloader($class) {
if (strpos($class, 'WebPConvert\\') === 0) {
require_once __DIR__ . '/webp-on-demand-2.inc';
}
}
spl_autoload_register('webpconvert_autoloader', true, true);
$source = $_GET['source']; // Absolute file path to source file. Comes from the .htaccess
$destination = $source . '.webp'; // Store the converted images besides the original images (other options are available!)
$options = [
// UNCOMMENT NEXT LINE, WHEN YOU ARE UP AND RUNNING!
'show-report' => true // Show a conversion report instead of serving the converted image.
// More options available!
// https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/converting/introduction-for-converting.md
// https://github.com/rosell-dk/webp-convert/blob/master/docs/v2.0/serving/introduction-for-serving.md
];
WebPConvert::serveConverted($source, $destination, $options);
```
Note that the procedure has changed in 2.0. In 1.x, the library supported a `require-for-conversion` option, but this option has been removed in 2.0. It was not really needed, as the example above illustrates.
### 3. Continue the regular install instructions from step 3
[Click here to continue...](https://github.com/rosell-dk/webp-on-demand#3-add-redirect-rules)