Skip to content

Commit

Permalink
Add a way to configure threshold
Browse files Browse the repository at this point in the history
  • Loading branch information
riasvdv committed Oct 30, 2024
1 parent 5b9b32a commit 28a2b22
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
16 changes: 15 additions & 1 deletion config/responsive-images.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
|
*/
'force_absolute_urls' => false,

/*
|--------------------------------------------------------------------------
| Queue
Expand All @@ -61,6 +61,20 @@

'max_width' => null,

/*
|--------------------------------------------------------------------------
| Dimension Calculator Threshold
|--------------------------------------------------------------------------
|
| Define the file size threshold at which the default
| dimension calculator decides to generate a new
| variant. By default, this is 30% smaller.
| Must be a value: 0 < x < 1
|
*/

'dimension_calculator_threshold' => 0.7,

/*
|--------------------------------------------------------------------------
| Placeholder
Expand Down
2 changes: 1 addition & 1 deletion src/ResponsiveDimensionCalculator.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected function calculateDimensions(int $assetFilesize, int $assetWidth, int
$pixelPrice = $predictedFileSize / $area;

while (true) {
$predictedFileSize *= 0.7;
$predictedFileSize *= config('statamic.responsive-images.dimension_calculator_threshold', 0.7);

$newWidth = (int) floor(sqrt(($predictedFileSize / $pixelPrice) / $ratioForFilesize));

Expand Down
19 changes: 18 additions & 1 deletion tests/Feature/DimensionCalculatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ function getWidths(Asset $asset, Breakpoint $breakpoint): array
]);
});

it('can calculate the optimized widths for different dimensions with a custom threshold', function () {
config()->set('statamic.responsive-images.dimension_calculator_threshold', 0.25);

$stubbedAsset = stubAsset(2400, 1800, 3000 * 1024);
$breakpoint = new Breakpoint($stubbedAsset, 'default', 0, []);

$widths = getWidths($stubbedAsset, $breakpoint);

expect($widths)->toEqual([
0 => 2400,
1 => 1200,
2 => 600,
3 => 300,
4 => 150,
]);
});

it('filters out widths to be less than max width specified in config', function() {
config()->set('statamic.responsive-images.max_width', 300);

Expand Down Expand Up @@ -205,4 +222,4 @@ function getWidths(Asset $asset, Breakpoint $breakpoint): array
$calculatedDimensions = app(DimensionCalculator::class)->calculateForImgTag($breakpoint);

expect($calculatedDimensions->getHeight())->toEqual(170);
});
});

0 comments on commit 28a2b22

Please sign in to comment.