oc-resizer-plugin/classes/ImageResizer.php

109 lines
3.1 KiB
PHP

<?php
namespace Aweos\Resizer\Classes;
use Aweos\Resizer\Lib\MediaPath;
use Aweos\Resizer\Models\Setting;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Collection;
use Intervention\Image\ImageManager;
use Media\Classes\MediaLibrary;
use October\Rain\Resize\Resizer;
use Storage;
class ImageResizer
{
private FilesystemAdapter $disk;
private string $uploadDir;
private MediaLibrary $media;
private MediaPath $file;
public function __construct(FilesystemAdapter $disk, string $uploadDir, MediaLibrary $media)
{
$this->disk = $disk;
$this->uploadDir = $uploadDir;
$this->media = $media;
}
public function generate(MediaPath $file): void
{
$this->file = $file;
$this->disk->put($this->file->versionsPath(), $this->file->get());
if ($this->file->compressor()->shouldGenerateVersions()) {
$this->generateVersions();
}
}
private function dimensions(): Collection
{
[$width, $height] = getimagesize($this->file->root());
return collect(compact('width', 'height'));
}
private function sizes(): Collection
{
$sizes = Setting::get('sizes');
return collect(array_column($sizes, 'aspect_ratio'))->map(
fn ($ratio) => collect(array_combine(['width', 'height'], explode('x', $ratio))),
);
}
private function possibleSizes(): Collection
{
$return = collect([]);
$ratios = collect();
$ratios->push($this->dimensions());
$ratios = $ratios->merge($this->sizes());
foreach (collect(Setting::get('breakpoints'))->push($this->dimensions()->get('width'))->unique() as $size) {
foreach ($ratios as $ratio) {
$height = $size * $ratio->get('height') / $ratio->get('width');
$return->push(collect([
'width' => round($size),
'height' => round($height),
]));
}
}
return $return;
}
private function generateVersions(): void
{
foreach ($this->possibleSizes() as $size) {
$temp = microtime().'.jpg';
$r = app(ImageManager::class)->make($this->file->root())
->fit($size->get('width'), $size->get('height'), fn ($constraint) => $constraint->upsize())
->save($this->disk->path($temp));
list($destWidth, $destHeight) = getimagesize($this->disk->path($temp));
$versionFilename = $this->file->versionsDirPath().
'/'.
$this->file->filename().
'-'.
$destWidth.
'x'.
$destHeight.
'.'.
$this->file->extension();
if ($this->disk->exists($versionFilename)) {
$this->disk->delete($versionFilename);
}
$this->disk->move($temp, $versionFilename);
}
foreach ($this->file->versions() as $version) {
$this->file->compressor()->make($this->disk->path($version->get('path')));
}
}
}