Last active
January 24, 2021 14:35
-
-
Save IlijaT/778a2a3da1e13f8c3ec267debee6dd8f to your computer and use it in GitHub Desktop.
Laravel Job Class that resizes images with a max width/height while keeping the original aspect ratio using Intervention library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Jobs; | |
use Illuminate\Bus\Queueable; | |
use Intervention\Image\Facades\Image; | |
use Illuminate\Queue\SerializesModels; | |
use Illuminate\Support\Facades\Storage; | |
use Illuminate\Queue\InteractsWithQueue; | |
use Illuminate\Foundation\Bus\Dispatchable; | |
use Illuminate\Contracts\Queue\ShouldQueue; | |
class ProcessImage implements ShouldQueue | |
{ | |
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; | |
public $imagePath; | |
/** | |
* Create a new job instance. | |
* | |
* @param string $imagePath | |
* @return void | |
*/ | |
public function __construct($imagePath) | |
{ | |
$this->imagePath = $imagePath; | |
} | |
/** | |
* Execute the job. | |
* | |
* @return void | |
*/ | |
public function handle() | |
{ | |
$maxWidth = 1024; // your max width | |
$maxHeight = 700; // your max height | |
$img = Storage::disk('public')->get($this->imagePath); | |
$image = Image::make($img); | |
// Set $maxWidth to null if width of upoading image is smaller than height | |
// Set $maxHeight to null if height of upoading image is smaller than width | |
$image->height() > $image->width() ? $maxWidth=null : $maxHeight=null; | |
$image->resize($maxWidth, $maxHeight, function ($constraint) { | |
$constraint->aspectRatio(); | |
}) | |
->insert(Storage::disk('public')->get('images/watermark.png'), 'center') // optional, if you need watermark | |
->encode('jpg', 75) | |
->limitColors(255); | |
Storage::disk('public')->put($this->imagePath, (string) $image); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment