Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

spatie/spatie.be

493 stars
1 code files
View spatie/spatie.be on GitHub

app/Support/MediaLibrary/FileSizeOptimizedWidthCalculator.php

Open in GitHub
use Spatie\MediaLibrary\ResponsiveImages\WidthCalculator\FileSizeOptimizedWidthCalculator as BaseFileSizeOptimizedWidthCalculator;
 
class FileSizeOptimizedWidthCalculator extends BaseFileSizeOptimizedWidthCalculator
{
public float $stepSize = 0.4;
 
public function calculateWidths(int $fileSize, int $width, int $height): Collection
{
$targetWidths = collect();
 
$targetWidths->push($width);
 
$ratio = $height / $width;
$area = $height * $width;
 
$predictedFileSize = $fileSize;
$pixelPrice = $predictedFileSize / $area;
 
while (true) {
$predictedFileSize *= $this->stepSize;
 
$newWidth = (int) floor(sqrt(($predictedFileSize / $pixelPrice) / $ratio));
 
if ($this->finishedCalculating((int) $predictedFileSize, $newWidth)) {
return $targetWidths;
}
 
$targetWidths->push($newWidth);
}
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.