---
tags: PHP, Backend, Laravel
disqus: HackMD
---
# Laravel Intervention/image 圖片處理
[Intervention/image](https://intervention.io/)是一個對圖像處理知名的庫,我們可以用它來創建縮圖,加上浮水印,格式化大型圖檔等等。
支援常見圖像處理庫像是[`GD Library`](https://www.php.net/manual/en/book.image.php)和[`imagemagick`](https://github.com/imagemagick/imagemagick)
## 安裝
```cmd=
php composer.phar require intervention/image
```
### 系統要求
* PHP >= 5.4
* Fileinfo Extension
---
以及以下其一圖像library
* GD Library (>=2.0) … or …
* Imagick PHP extension (>=6.5.7)
## 配置
發布配置指令
```cmd=
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"
```
我們可以找到此檔案`app/config/packages/intervention/image/config.php`
可以選擇要使用哪一個圖像庫做驅動`gd`或是`imagick`
`Intervention/image`默認是用`PHP`的`GD Library`來進行圖像處理,但在處理效率上`imagemagick`稍勝於`gd`,所以推薦可以換成`imagemagick`來進行圖像處理。
```php=
'driver' => 'gd'
```
## 圖像處理範例
### 基本功能
```php=
use Intervention\Image\Facades\Image;
// 圖片路徑
$path = 'public/example.jpg'
// 圖片檔案
$img = Image::make($path)
// 調整大小
$img->resize(320, 240);
// 插入浮水印
$img->insert('public/watermark.png');
// 儲存檔案
$img->save('public/bar.jpg');
```
### 調整圖片大小範例
假設原圖如下(8.60 MB),我們可以調整他的大小並儲存為`webp`格式,那`webp`格式又是甚麼,簡單來說就是在減少檔案大小的同時,達到和`JPEG`、`PNG`、`GIF`格式相同的圖片品質。

(圖片來自`https://wall.alphacoders.com/`)
固定寬度為`400`,高度等比例縮放,並以`95%`品質儲存為`webp`檔案格式,調整過後檔案大小為`39kb`
```php=
use Intervention\Image\Facades\Image;
$photo = Image::make($request->file('image'))
->resize(400, null, function ($constraint) {
$constraint->aspectRatio();
})
->encode('webp', 95)
->save('public/2077.webp');
```

(此用`jpg`檔案代替一下)
### 剪裁圖片
```php=
use Intervention\Image\Facades\Image;
Image::make($request->file('image'))
->crop(1000, 1000, 400, 400)
->encode('jpg', 95);
```

### 插入浮水印
在右下角插入聖誕老人
```php=
use Intervention\Image\Facades\Image;
Image::make($request->file('image'))
->insert('img/santa-claus.png', 'bottom-right', 40, 40)
->encode('jpg', 95);
```

### 動態處理圖片
我們可以透過`HTTP`方式訪問圖像,使用這種方式一張照片只需上傳一次,透過對其調整大小剪裁等等,即可得到不同尺寸圖片
```php=
use Illuminate\Support\Facades\Route;
use Intervention\Image\Facades\Image;
Route::get('/image/manipulaton/{name}/{width?}/{height?}', function (\Illuminate\Http\Request $request) {
$name = $request->name;
// 根據路路徑載入圖片
$img = Image::make("img/$name");
// 圖像處理
$img->resize($request->width, $request->height, function ($constraint) {
$constraint->aspectRatio();
});
// c創建response,及圖像編碼
$response = Response::make($img->encode('webp',));
// 設置 content-type
$response->header('Content-Type', 'image/webp');
// 回傳
return $response;
});
```
假設要取得寬 x 高為 400 x 500的圖像,即可透過訪問以下網址取得
```
/image/manipulaton/imagename/400/500
```
## 更多功能
查看更多API,前往[intervention.io](https://image.intervention.io/v2)