Intervention Image 縮小上傳圖片

WICOgohome
Aug 31, 2018 · 3 min read

在運用使用者上傳的圖片時,可以視呈現情況決定使用的圖片大小,減低使用者載入圖片的負擔。

Intervention Image

【安裝】

$ composer require intervention/image

官網有貼心的laravel安裝說明:

config/app.php

$providers:Intervention\Image\ImageServiceProvider::class
$aliases:‘Image’ => Intervention\Image\Facades\Image::class

Static Example

use Intervention\Image\ImageManagerStatic as Image;

【resize】

$img = Image::make('baz.jpg'); //從暫存資料夾讀取照片資訊

因為主要使用的地方為縮圖和輸出word,並且不能讓圖片變形,因此只設定寬度

※若使用$img->resize(300); 圖片會直接變形

使用官方提供的方法:

//將尺寸調整為寬度300px(高度等比例自動調整)
$img->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});

就能輕鬆建立較小的圖片檔,再以save(‘path/檔名’)存檔

//剪裁大小
public function resize_upload_file($file, $file_name, $path)
{
Image::make($file)->resize(830, null, function ($constraint) {
$constraint->aspectRatio();
})->save(public_path().$path.'export_to_word/'.$file_name);

}
WICOgohome

Written by

Studying

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade