81 lines
2.6 KiB
PHP
Executable File
81 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Api;
|
|
|
|
use App\Support\Uploads;
|
|
use Carbon\Carbon;
|
|
use Intervention\Image\Facades\Image as Imagee;
|
|
|
|
class ImageResize
|
|
{
|
|
/**
|
|
* @param string $type
|
|
* @return string relative path used as S3 key, e.g. uploads/posters/thumbs/2024/01/01
|
|
*/
|
|
private function thumbFolder(string $type): string
|
|
{
|
|
$folder = Carbon::now()->format('Y/m/d');
|
|
return "uploads/{$type}/thumbs/{$folder}";
|
|
}
|
|
|
|
/**
|
|
* Resize an image and upload to S3/MinIO (or save locally).
|
|
*
|
|
* @param string $path Relative path of the source image (from 'public' disk = storage/app/public/)
|
|
* @param int $size Target width in pixels
|
|
* @param string $type Subfolder name (posters, screens, brands …)
|
|
* @param bool $deleteOriginal Delete the source file after resizing
|
|
* @return string Relative path (S3 key) of the generated thumb
|
|
*/
|
|
public function resize(string $path, int $size, string $type, bool $deleteOriginal = false): string
|
|
{
|
|
// 1. Locate the source file (stored via ->store('temp', 'public'))
|
|
$srcPath = storage_path('app/public/' . $path);
|
|
|
|
if (!file_exists($srcPath)) {
|
|
throw new \Exception("Source image not found: {$srcPath}");
|
|
}
|
|
|
|
// 2. Resize into a temp file in storage/app/public/tmp/
|
|
$tmpDir = storage_path('app/public/tmp');
|
|
if (!is_dir($tmpDir)) {
|
|
mkdir($tmpDir, 0775, true);
|
|
}
|
|
|
|
$thumbFilename = basename($path);
|
|
$tmpThumb = "{$tmpDir}/{$thumbFilename}";
|
|
|
|
$img = Imagee::make($srcPath);
|
|
$img->resize($size, null, function ($constraint) {
|
|
$constraint->aspectRatio();
|
|
});
|
|
$img->save($tmpThumb, 90);
|
|
|
|
// 3. Upload thumb to S3/MinIO
|
|
$thumbKey = $this->thumbFolder($type) . '/' . $thumbFilename;
|
|
|
|
if (config('filesystems.default') === 's3') {
|
|
Uploads::put($thumbKey, file_get_contents($tmpThumb), 's3');
|
|
} else {
|
|
// Local: move to public/uploads/…/thumbs/…
|
|
$localDir = public_path(dirname($thumbKey));
|
|
if (!is_dir($localDir)) {
|
|
mkdir($localDir, 0775, true);
|
|
}
|
|
rename($tmpThumb, public_path($thumbKey));
|
|
}
|
|
|
|
// 4. Clean up tmp thumb
|
|
if (file_exists($tmpThumb)) {
|
|
unlink($tmpThumb);
|
|
}
|
|
|
|
// 5. Clean up original temp file if requested
|
|
if ($deleteOriginal && file_exists($srcPath)) {
|
|
unlink($srcPath);
|
|
}
|
|
|
|
return $thumbKey;
|
|
}
|
|
}
|