Skip to content

Commit

Permalink
Improved tests and documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
martinheise committed Jul 24, 2024
1 parent 1cbca43 commit 0e7647a
Show file tree
Hide file tree
Showing 7 changed files with 248 additions and 83 deletions.
67 changes: 62 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ This module contains logic to calculate multiple scaled image sizes from one sou

It only contains business logic to define the expected sizes. The actual handling of the image data, like resizing, caching of the result etc. is not handled by the module, but done by the calling code, the interface `ImageData` serves as main connection point.

## Background

“Humans shouldn’t be doing this” – some inspiring thoughts on deciding which image resolutions to use in responsive output can be found in this article by Jason Grigsby: [Image Breakpoints](https://cloudfour.com/thinks/responsive-images-101-part-9-image-breakpoints/), especially [Setting image breakpoints based on a performance budget](https://cloudfour.com/thinks/responsive-images-101-part-9-image-breakpoints/#setting-image-breakpoints-based-on-a-performance-budget)

## Installation

Install with composer:
Expand All @@ -13,19 +17,72 @@ Install with composer:
## Usage overview

- Implement interface `Mhe\Imagetools\Data\ImageData` as a wrapper for your images and processing methods
- create a `Mhe\Imagetools\Data\RenderConfig` object holding options and context information like the specific image layout context
- create a `Mhe\Imagetools\Data\RenderConfig` object holding options and context information about the specific image layout context:
```
$config = new RenderConfig("max-width: 1000px) 100vw, 1000px", 5, 20000, 2);
$config = new RenderConfig("(max-width: 1000px) 100vw, 1000px");
```
- create a new `Mhe\Imagetools\ImageResizer` and let it process the source image with given configuration:
```
$resizer = new ImageResizer();
$result = $resizer->getVariants($srcimg, $config);
```
- The result is an array of images you will usually use to output a `srcset` attribute
- The result is an array of images you can use to output a `srcset` attribute

For a small demonstration of the very basic usage see [mhe/imagetools-cli](https://github.com/martinheise/imagetools-cli).

A more advanced usage is [mhe/silverstripe-responsiveimages](https://github.com/martinheise/silverstripe-responsiveimages), a module for CMS Silverstripe.

## Configuration and options

### ImageResizer options

When creating a new `ImageResizer` you can provide these parameters to tweak the general behaviour:

- `min_viewport_width`: minimum viewport width to consider (default: 320)
- `max_viewport_width`: maximum viewport width to consider, e.g. for fullwidth images (default: 2400)
- `rem_size`: used to translate values in rem unit to px (default: 16)

### RenderConfig options

A `RenderConfig` contains several options used for the calculations for a specific image – usually they are the same for multiple images used in the same layout context and/or CSS class, so you would have one configuration for Hero images, one for slider images, one for teaser images etc.

#### sizes

The main parameter of `RenderConfig`. It matches the `sizes` attribute of a desired `ìmg` element, telling the ImageResizer in which actual layout sizes (widths) the image will output on different screensizes.

This information can be deducted from the page layout usually defined in CSS, depending on the complexity of your layout it can get a bit more complicated to count in all conditions, often you just have to add up a couple of container margins etc. In doubt: if the information don’t exactly match the image sizes it probably doesn’t effect the result very much – a rough approximation is better than no information.

*Some examples:*

Full width image with margins of 16px on each side:

```calc(100vw - 32px)```

Image has full width with margins in mobile view, displayed in a 2-column grid on desktop:

```(max-width: 720px) calc(100vw - 32px), calc(50vw - 40px)```

Image has full width with margins in mobile view, displayed in a 2-column grid on desktop, and is limited to a fixed width on large screens:

```(max-width: 720px) calc(100vw - 32px), (max-width: 1680px) calc(50vw - 40px), 800px```

#### sizediff

This is the desired filesize difference in bytes between two different renditions. It will not be reached exactly, but rather a rough target.

Lower values mean more generated files, better matching the particular user conditions, but of course more load on generating images.

#### maxsteps

Set a limit on the number of renditions generated, has precedence of `sizediff`. With low `sizediff` values and large images this will assure that you don’t end up with vast amount of images generated.

#### retinalevel

Set to either `2` or `3`adds up extra levels for high resolution screens. If e.g. the maximum calculated image width is 1200px, also renditions for 2400px are created.

For a small demonstration of the very basic usage see `mhe/imagetools-cli`.
#### rendersizes

A more advanced usage is `mhe/silverstripe-responsiveimages`, a module for CMS Silverstripe.
Request specific image widths to generate for specific purposes. If given the other parameters are ignored.

Can be helpful in specific cases – if you _only_ use this kind of configuration you probably don’t need this module at all ...

9 changes: 7 additions & 2 deletions src/Calculations/CssCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,11 @@ public function setRemSize($rem_size): void

/**
* calculates given image sizes for different width breakpoints, according media-query
* returns entries for each breakpoint (below and above point) and the minimum and maximum viewport widths
* @internal may change in the future, public only for testing
*
* @param $string string, e.g. "(width > 1600px) 800px, (width > 800px) 40vw, 80vw"
* @return array
* @return array associative array in the form [ viewportwidth => imagewidth ... ]
*/
public function calculateBreakpointValues($string)
{
Expand All @@ -96,7 +97,7 @@ public function calculateBreakpointValues($string)

foreach ($sizetokens as $token) {
$range = $this->calculateBreakpointRange($token, $minbp, $maxbp);
if (is_array($range)) {
if (is_array($range) and count($range) > 1) {
$bps = array_keys($range);
// limit breakpoints for next step
if ($bps[0] > $minbp) {
Expand All @@ -112,6 +113,10 @@ public function calculateBreakpointValues($string)
}
}
}
if (count($ranges) == 0) {
$ranges[$minbp] = $minbp;
$ranges[$maxbp] = $maxbp;
}
return $ranges;
}

Expand Down
27 changes: 23 additions & 4 deletions src/Data/RenderConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/
class RenderConfig
{
protected string $sizesstring;
protected string $sizes;
protected int $maxsteps;
protected int $sizediff;
protected int $retinalevel;
Expand All @@ -22,7 +22,7 @@ class RenderConfig
*/
public function __construct(string $sizes, int $maxsteps = 10, int $sizediff = 50000, int $retinalevel = 1, array $rendersizes = [])
{
$this->sizesstring = $sizes;
$this->sizes = $sizes;
$this->maxsteps = $maxsteps;
$this->sizediff = $sizediff;
$this->retinalevel = $retinalevel;
Expand Down Expand Up @@ -55,17 +55,36 @@ private function validateValues(): void
/**
* @return string
*/
public function getSizes(): string
{
return $this->sizes;
}

/**
* @param string $sizes
*/
public function setSizes(string $sizes): void
{
$this->sizes = $sizes;
$this->validateValues();
}

/**
* @return string
* @deprecated Use getSizes() instead
*/
public function getSizesstring(): string
{
return $this->sizesstring;
return $this->sizes;
}

/**
* @param string $sizesstring
* @deprecated Use getSizes() instead
*/
public function setSizesstring(string $sizesstring): void
{
$this->sizesstring = $sizesstring;
$this->sizes = $sizesstring;
$this->validateValues();
}

Expand Down
4 changes: 2 additions & 2 deletions src/ImageResizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@ public function getVariants(ImageData $srcimage, RenderConfig $config): array
// ToDo: support configured image ratio ?
$ratio = null;

$sizevalues = $this->cssCalculator->calculateBreakpointValues($config->getSizesstring());
$sizevalues = $this->cssCalculator->calculateBreakpointValues($config->getSizes());

$minwidth = min(array_values($sizevalues));
$maxwidth = max(array_values($sizevalues));

// prevent upscaling
// ToDo: check logic, especially for retina
// ToDo: check logic, especially for retina – retina will still be upscaled this way!
$maxwidth = min($maxwidth, $srcimage->getWidth());
if ($maxwidth < $minwidth) {
$minwidth = $maxwidth;
Expand Down
119 changes: 63 additions & 56 deletions tests/Calculations/CssCalculatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,69 @@ public function testCalculateCssExpressionValue()
$this->assertNull($calculator->calculateCssExpressionValue('(width > 5rem) calc(80vw - 30px)'));
}

public function testCalculateBreakpointValues()
{
$calculator = new CssCalculator(120, 2400);
// ascending sizes
$this->assertEquals(
[
120 => 96,
800 => 640,
801 => 320,
1600 => 640,
1601 => 800,
2400 => 800
],
$calculator->calculateBreakpointValues('(width <= 800px) 80vw, (width <= 1600px) 40vw, 800px')
);
// descending sizes
$this->assertEquals(
[
2400 => 800,
1601 => 800,
1600 => 640,
801 => 320,
800 => 640,
120 => 96,
],
$calculator->calculateBreakpointValues('(width > 1600px) 800px, (width > 800px) 40vw, 80vw')
);
// descending sizes with calc
$this->assertEquals(
[
2400 => 810,
1617 => 810,
1616 => 636,
801 => 310,
800 => 660,
120 => 116,
],
$calculator->calculateBreakpointValues('(width > calc(1600px + 1rem)) calc(50rem + 10px), (width > 800px) calc(40vw - 10px), calc(80vw + 20px)')
);
// descending sizes with periods
$this->assertEquals(
[
2400 => 493,
1680 => 493,
1679 => 493,
1020 => 273,
1019 => 410,
760 => 280,
759 => 727,
120 => 88
],
$calculator->calculateBreakpointValues('(min-width: 1680px) 493px, (min-width: 1020px) calc(33.33vw - 66.67px), (min-width: 760px) calc(50vw - 100px), calc(100vw - 32px)')
);
// fallback to min/max viewport for invalid input
$this->assertEquals(
[
2400 => 2400,
120 => 120
],
$calculator->calculateBreakpointValues('(min-width: 1680px) 493px 322px')
);
}

public function testCalculateBreakpointRange()
{
$calculator = new CssCalculator(120, 2400);
Expand Down Expand Up @@ -115,60 +178,4 @@ public function testCalculateBreakpointRange()
$calculator->calculateBreakpointRange('what is this')
);
}


public function testCalculateBreakpointValues()
{
$calculator = new CssCalculator(120, 2400);
// ascending sizes
$this->assertEquals(
[
120 => 96,
800 => 640,
801 => 320,
1600 => 640,
1601 => 800,
2400 => 800
],
$calculator->calculateBreakpointValues('(width <= 800px) 80vw, (width <= 1600px) 40vw, 800px')
);
// descending sizes
$this->assertEquals(
[
2400 => 800,
1601 => 800,
1600 => 640,
801 => 320,
800 => 640,
120 => 96,
],
$calculator->calculateBreakpointValues('(width > 1600px) 800px, (width > 800px) 40vw, 80vw')
);
// descending sizes with calc
$this->assertEquals(
[
2400 => 810,
1617 => 810,
1616 => 636,
801 => 310,
800 => 660,
120 => 116,
],
$calculator->calculateBreakpointValues('(width > calc(1600px + 1rem)) calc(50rem + 10px), (width > 800px) calc(40vw - 10px), calc(80vw + 20px)')
);
// descending sizes with periods
$this->assertEquals(
[
2400 => 493,
1680 => 493,
1679 => 493,
1020 => 273,
1019 => 410,
760 => 280,
759 => 727,
120 => 88
],
$calculator->calculateBreakpointValues('(min-width: 1680px) 493px, (min-width: 1020px) calc(33.33vw - 66.67px), (min-width: 760px) calc(50vw - 100px), calc(100vw - 32px)')
);
}
}
4 changes: 2 additions & 2 deletions tests/Data/DummyImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ public function getFilesize(): int
*/
public function getPublicPath(): string
{
return "dummy_" . $this->getWidth() . "_" . $this->getFilesize(). ".jpg";
return "dummy_" . $this->getWidth() . "_" . $this->getFilesize() . ".jpg";
}

/**
* @inheritDoc
*/
public function resize($width): ImageData
{
$filesize = $this->getFilesize() / ($this->width / $width)^2;
$filesize = round($this->getFilesize() / ($this->width / $width) ** 2);
return new DummyImage($width, $filesize);
}
}
Loading

0 comments on commit 0e7647a

Please sign in to comment.