Laravel 中使用 Intervention 缩放图片/生成缩略图

Laravel 中使用 Intervention 库缩放图片的时候,没必要用专供的接口,用通用不需要任何配置,还更简单,直接调用就可以。

step 1、composer 安装 Intervention

composer require intervention/image

step 2、调用 Intervention API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

namespace App\Foundation;

use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic;

class ImageHelper
{
/**
* 生成缩略图。
* 指定宽高则缩放后裁剪,只指定宽或高则等比缩小。
* @param string $orgPath 原图路径
* @param string $targetPath 小图保存路径
*/
public static function thumb(string $orgPath, string $targetPath, int|null $width, int|null $height): bool
{
$img = ImageManagerStatic::make($orgPath);

$width || $width = null;
$height || $height = null;

if ($width && $height) {
// 指定宽高,缩小到合适的大小,再把超过去的部分裁剪掉
$img->fit($width, $height, function ($constraint) {
$constraint->upsize(); // 防止缩略图比原图大
});
} else {
// 只指定宽或高,等比缩小
$img->resize($width, $height, function ($constraint) {
$constraint->aspectRatio(); // 自动等比缩放
$constraint->upsize(); // 防止缩略图比原图大
});
}

return Storage::put(
$targetPath,
$img->encode('jpg')->getEncoded()
);
}
}

Laravel 中使用 Intervention 缩放图片/生成缩略图

https://coderpan.com/php/laravel-intervention-resize-image.html

作者

CoderPan

发布于

2023-03-04

更新于

2024-05-08

许可协议

评论