Skip to content

Commit

Permalink
Commit initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
martinheise committed Jul 19, 2024
0 parents commit 75aefcd
Show file tree
Hide file tree
Showing 16 changed files with 1,150 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# For more information about the properties used in this file,
# please see the EditorConfig documentation:
# http://editorconfig.org

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/vendor/
.DS_Store
# ignore special IDE files
.idea/workspace.xml
.idea/tasks.xml
.idea/dataSources.ids
.idea/datasources.xml
.phpunit.result.cache
12 changes: 12 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Copyright (c) 2024 Martin Heise <info@martinheise.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Image tools

This module contains logic to calculate multiple scaled image sizes from one source image and configuration options. It is meant to create appropriate `srcset`and `sizes` attributes for responsive images that best fit the given image and information about the HTML/CSS context.

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.

## Installation

## 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
```
$config = new RenderConfig("max-width: 1000px) 100vw, 1000px", 5, 20000, 2);
```
- 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

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

A more advanced usage is `mhe/silverstripe-responsiveimages`, a module for CMS Silverstripe.


22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "mhe/imagetools",
"description": "Tools for generating responsive images",
"authors": [
{
"name": "Martin Heise",
"email": "info@martinheise.de"
}
],
"require": {
"php": "^8.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"Mhe\\Imagetools\\": "src/",
"Mhe\\Imagetools\\Tests\\": "tests/"
}
}
}
12 changes: 12 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="PSR-12-adjusted">
<description>CodeSniffer ruleset for adjusted PSR-12 coding conventions.</description>

<file>src</file>
<file>tests</file>

<!-- base rules are PSR-12 -->
<rule ref="PSR12" >
<exclude name="Generic.Files.LineLength.TooLong" />
</rule>
</ruleset>
5 changes: 5 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<phpunit colors="true">
<testsuite name="Default">
<directory>tests</directory>
</testsuite>
</phpunit>
253 changes: 253 additions & 0 deletions src/Calculations/CssCalculator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
<?php

namespace Mhe\Imagetools\Calculations;

/**
* Helper class to parse specific CSS information and perform calculations based on it
*/
class CssCalculator
{
protected $min_viewport_width;
protected $max_viewport_width;
protected $rem_size;

/**
* @var MathParser
*/
protected $mathparser;

/**
* Create a new CssCalculator with given base properties
* @param $min_viewport_width int Minimum viewport width to consider for calculations
* @param $max_viewport_width int Maximum viewport width to consider for calculations
* @param $rem_size int Default font size to use for calculations of values given in rem units
*/
public function __construct($min_viewport_width = 320, $max_viewport_width = 2400, $rem_size = 16)
{
$this->min_viewport_width = $min_viewport_width;
$this->max_viewport_width = $max_viewport_width;
$this->rem_size = $rem_size;
$this->mathparser = new MathParser();
}

/**
* @return int
*/
public function getMinViewportWidth()
{
return $this->min_viewport_width;
}

/**
* @param int $min_viewport_width
*/
public function setMinViewportWidth($min_viewport_width): void
{
$this->min_viewport_width = $min_viewport_width;
}

/**
* @return int
*/
public function getMaxViewportWidth()
{
return $this->max_viewport_width;
}

/**
* @param int $max_viewport_width
*/
public function setMaxViewportWidth($max_viewport_width): void
{
$this->max_viewport_width = $max_viewport_width;
}

/**
* @return int
*/
public function getRemSize()
{
return $this->rem_size;
}

/**
* @param int $rem_size
*/
public function setRemSize($rem_size): void
{
$this->rem_size = $rem_size;
}

/**
* calculates given image sizes for different width breakpoints, according media-query
* @internal may change in the future, public only for testing
*
* @param $string string, e.g. "(width > 1600px) 800px, (width > 800px) 40vw, 80vw"
* @return array
*/
public function calculateBreakpointValues($string)
{
$sizetokens = preg_split('/,\s*/', $string);

$minbp = $this->min_viewport_width;
$maxbp = $this->max_viewport_width;

$ranges = [];

foreach ($sizetokens as $token) {
$range = $this->calculateBreakpointRange($token, $minbp, $maxbp);
if (is_array($range)) {
$bps = array_keys($range);
// limit breakpoints for next step
if ($bps[0] > $minbp) {
$maxbp = $bps[0] - 1;
} elseif ($bps[1] < $maxbp) {
$minbp = $bps[1] + 1;
}
if (!isset($ranges[$bps[0]])) {
$ranges[$bps[0]] = $range[$bps[0]];
}
if (!isset($ranges[$bps[1]])) {
$ranges[$bps[1]] = $range[$bps[1]];
}
}
}
return $ranges;
}

/**
* calculates given image size for min and max values of one breakpoint range
* @internal may change in the future, public only for testing
*
* @param string $string e.g. "(width > 1600px) 800px" or "100vw"
* @param int $minbp lower limit for calculation range
* @param null $minbp upper limit for calculation range
* @return array
*/
public function calculateBreakpointRange($string, $minbp = null, $maxbp = null)
{
$min = $minbp ?: $this->min_viewport_width;
$max = $maxbp ?: $this->max_viewport_width;

$range = [];

if (preg_match('/^\s*\((.*)\)\s+(.*)/', $string, $matches)) {
// with query
$query = $this->calculateCssExpression($matches[1]);

if (preg_match('/(max-width:|width\s*<=)\s*(\d+)/', $query, $cond)) {
$max = min($max, (int)$cond[2]);
}
if (preg_match('/(width\s*<?)\s*(\d+)/', $query, $cond)) {
$max = min($max, (int)$cond[2] - 1);
}
if (preg_match('/(min-width:|width\s*>=)\s*(\d+)/', $query, $cond)) {
$min = max($min, (int)$cond[2]);
}
if (preg_match('/(width\s*>?)\s*(\d+)/', $query, $cond)) {
$min = max($min, (int)$cond[2] + 1);
}

if (!empty($val = $this->calculateCssExpressionValue($matches[2], $min))) {
$range[$min] = round($val);
}
if (!empty($val = $this->calculateCssExpressionValue($matches[2], $max))) {
$range[$max] = round($val);
}
} else {
// without query, using full given range
if (!empty($val = $this->calculateCssExpressionValue($string, $min))) {
$range[$min] = round($val);
}
if (!empty($val = $this->calculateCssExpressionValue($string, $max))) {
$range[$max] = round($val);
}
}
return $range;
}

/**
* Perform calculations on a CSS expression
* convert unit values to px-based numbers and evaluate calc() expressions
*
* @param string $expression CSS expression
* @param int $basevw base viewport width
* @param int $basevh base viewport height
* @return string result with replacement of valid values/calculations
*/
public function calculateCssExpression($expression, $basevw = null, $basevh = null)
{
$basevw = $basevw ?: $this->max_viewport_width;
$basevh = $basevh ?: round($this->max_viewport_width * 9 / 16);

// convert unit expression to px numbers
// not supported yet: percentage (would need ancestor context) – and other units
$step1 = preg_replace_callback('/([\d.]+)(rem|em|px|vh|vw)/', function ($matches) use ($basevw, $basevh) {
return $this->replaceUnitValue($matches, $basevw, $basevh);
}, $expression);

$step2 = preg_replace_callback('/calc\((.*?)\)/', function ($matches) {
return $this->replaceCalc($matches);
}, $step1);
return $step2;
}

/**
* calculate CSS expression to numeric (px-based) value
*
* @param string $expression CSS expression
* @param int $basevw base viewport width
* @param int $basevh base viewport height
* @return float|null value in px, or null if the expression could not be reduced to a simple numerical value
*/
public function calculateCssExpressionValue($expression, $basevw = null, $basevh = null)
{
$value = $this->calculateCssExpression($expression, $basevw, $basevh);
return is_numeric($value) ? floatval($value) : null;
}

/**
* Replace values including units with number value based on px, for use in `preg_replace_callback`
*
* @param string $matches submatches [expression, value, unit]
* @param int $basevw base viewport width
* @param int $basevh base viewport height
* @return string
*/
protected function replaceUnitValue($matches, $basevw, $basevh)
{
if ($matches[2] == 'px') {
return $matches[1];
}
$num = (double) $matches[1];
$converted = $num;
switch ($matches[2]) {
case "rem":
case "em":
$converted = $num * $this->rem_size;
break;
case "vw":
$converted = $num * $basevw / 100;
break;
case "vh":
$converted = $num * $basevh / 100;
break;
default:
return $matches[0];
}
return strval($converted);
}

/**
* replace CSS calc() expression with calculated numerical value, for use in `preg_replace_callback`
* single values need to be converted to numbers already
*
* @param string $matches submatches [expression, calc-content]
* @return float|int|mixed
*/
protected function replaceCalc($matches)
{
$value = $this->mathparser->calculate($matches[1]);
return $value ?: $matches[1];
}
}
Loading

0 comments on commit 75aefcd

Please sign in to comment.