Created
January 27, 2020 18:57
-
-
Save amir9480/774ca02826324c23135152fbbe93d04d to your computer and use it in GitHub Desktop.
Image resizer in laravel.
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\Http\Controllers; | |
use Illuminate\Support\Facades\File; | |
use Intervention\Image\Facades\Image; | |
use Exception; | |
class ImageController extends Controller | |
{ | |
/** | |
* Get resized image. | |
* | |
* @param string $size | |
* @param string $imagePath | |
* @return \Illuminate\Http\Response | |
*/ | |
public function resizedImage(string $size, string $imagePath) | |
{ | |
$width = 0; | |
$height = 0; | |
switch ($size) { | |
case 'small': | |
$width = 360; | |
$height = 120; | |
break; | |
default: | |
return abort(404); | |
} | |
if (! File::exists(public_path("uploads/".$imagePath))) { | |
return abort(404); | |
} | |
$extension = pathinfo($imagePath, PATHINFO_EXTENSION); | |
try { | |
$image = Image::make(public_path("uploads/".$imagePath)); | |
} catch (Exception $e) { | |
abort(404); | |
} | |
if ($width && $height) { | |
$image->fit($width, $height); | |
} | |
if (! File::isDirectory(public_path("uploads/resized-images/".$size."/".pathinfo($imagePath, PATHINFO_DIRNAME)))) { | |
File::makeDirectory(public_path("uploads/resized-images/".$size."/".pathinfo($imagePath, PATHINFO_DIRNAME)), 0755, true); | |
} | |
if ($extension == "jpeg" || $extension == "jpg") { | |
$image->interlace(); | |
} | |
$image->save(public_path("uploads/resized-images/".$size."/".$imagePath), 100); | |
return $image->response(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment