Yêu cầu
Để tối ưu ảnh khi hiển thị trên nhiều thiết bị khác nhau. Khi người dùng upload 1 hình ảnh bất kỳ. Thông thường chúng ta sẽ:
- Tự động sinh ra nhiều file ảnh bằng cách điều chỉnh kích cỡ (resize ảnh).
- Được đặt tên theo quy cách
ten_file_anh_rong_x_cao
Ví dụ: người dùng upload file ảnh hoa-hong.jpg , có kích thước thực của file ảnh là 3200x1900 px. Chúng ta sẽ tự sinh ra các file như sau:
hoa-hong.jpg
hoa-hong-100x100.jpg
hoa-hong-150x150.jpg
hoa-hong-300x169.jpg
hoa-hong-450x450.jpg
hoa-hong-600x338.jpg
hoa-hong-768x432.jpg
hoa-hong-1024x576.jpg
- ...
Các bước thực hiện
Để thuận tiện chúng ta sẽ sử dụng thư viện hiệu chỉnh ảnh nổi tiếng của PHP là https://github.com/Intervention/image
Step 1: cài đặt thư viện
Gõ câu lệnh vào cmd:
composer require intervention/image
Step 2: bật cấu hình sử dụng thư viện Intervention Image
Hiệu chỉnh file config/app.php
return [
......
......
$provides => [
......,
Intervention\Image\ImageServiceProvider::class
],
$aliases => [
.....,
'Image' => Intervention\Image\Facades\Image::class
]
]
Step 3: bổ sung bước xử lý lưu ảnh theo tỷ lệ mong muốn trong Action của Controller thích hợp
/**
* Image resize
*/
public function imgResize(Request $request)
{
$image = $request->file('imgFile');
$input['imagename'] = time().'.'.$image->extension();
$filePath = public_path('/thumbnails');
$img = Image::make($image->path());
$img->resize(110, 110, function ($const) {
$const->aspectRatio();
})->save($filePath.'/'.$input['imagename']);
$filePath = public_path('/images');
$image->move($filePath, $input['imagename']);
return back()
->with('success','Image uploaded')
->with('fileName',$input['imagename']);
}
|