89 lines
2.6 KiB
PHP
Executable File
89 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Api;
|
|
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Intervention\Image\Facades\Image as Imagee;
|
|
|
|
class ImageResize
|
|
{
|
|
/**
|
|
* @param string $type
|
|
* @return string
|
|
*/
|
|
private function mkdir(string $type)
|
|
{
|
|
$folder = Carbon::now()->format('Y/m/d');
|
|
$path = "uploads/{$type}/thumbs/{$folder}";
|
|
|
|
if (!file_exists(public_path($path))) {
|
|
mkdir(public_path($path), 0775, true);
|
|
}
|
|
|
|
return $path;
|
|
}
|
|
|
|
/**
|
|
* @param $path
|
|
* @param $size
|
|
* @param $type
|
|
* @param bool $deleteOriginal
|
|
* @return string
|
|
* @throws \Exception
|
|
*/
|
|
public function resize($path, $size, $type, $deleteOriginal = false)
|
|
{
|
|
// 1. Resolve source path
|
|
$srcPath = file_exists(public_path($path))
|
|
? public_path($path)
|
|
: storage_path('app/public/' . $path);
|
|
|
|
if (!file_exists($srcPath)) {
|
|
if (file_exists($path)) {
|
|
$srcPath = $path;
|
|
} else {
|
|
// Last ditch effort: try to get from S3 if it's not local
|
|
if (env('FILESYSTEM_DISK') == 's3' && Storage::disk('s3')->exists($path)) {
|
|
$fileContent = Storage::disk('s3')->get($path);
|
|
$tmpLocal = storage_path('app/public/temp_' . basename($path));
|
|
file_put_contents($tmpLocal, $fileContent);
|
|
$srcPath = $tmpLocal;
|
|
$deleteOriginal = true; // Clean up the temp download
|
|
} else {
|
|
throw new \Exception("Source image not found: " . $path);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Prepare thumb destination
|
|
$name = basename($path);
|
|
$folder = $this->mkdir($type);
|
|
$path_thumb = "{$folder}/{$name}";
|
|
$absPathThumb = public_path($path_thumb);
|
|
|
|
// 3. Resize and Save Thumb
|
|
$img = Imagee::make($srcPath);
|
|
$img->resize($size, null, function ($constraint) {
|
|
$constraint->aspectRatio();
|
|
});
|
|
$img->save($absPathThumb, 100);
|
|
|
|
// 4. Handle S3 Upload
|
|
if (env('FILESYSTEM_DISK') == 's3') {
|
|
Storage::disk('s3')->put($path_thumb, file_get_contents($absPathThumb));
|
|
// Remove local thumb after S3 upload
|
|
if (file_exists($absPathThumb)) {
|
|
unlink($absPathThumb);
|
|
}
|
|
}
|
|
|
|
// 5. Cleanup original if requested
|
|
if ($deleteOriginal && file_exists($srcPath)) {
|
|
unlink($srcPath);
|
|
}
|
|
|
|
return $path_thumb;
|
|
}
|
|
}
|