英文:
Resize image before uploading in Laravel 5.8
问题
如何在上传之前将图像调整为最大边为500px的大小?
英文:
I have this function for upload image via api in Laravel:
private function handleImage($image)
{
$exploded = explode(',', $image);
$decoded = base64_decode($exploded[1]);
if (Str::contains($exploded[0], 'jpeg')) {
$extension = 'jpg';
} else {
$extension = 'png';
}
$fileName = Str::random() . '.' . $extension;
$path = public_path() . '/images/products/' . $fileName;
$file = file_put_contents($path, $decoded);
$image = '/images/products/' . $fileName;
return $image;
}
How can I resize image to size with max side 500px before uploading?
答案1
得分: 1
You can try the Intervention Image package in Laravel to resize before uploading.
-
安装该包:
composer require intervention/image
-
在你的文件开头添加以下代码来导入所需的类:
use Intervention\Image\ImageManagerStatic as Image;
use Illuminate\Support\Str;
-
修改 handleImage 方法如下:
private function handleImage($image) { $exploded = explode(',', $image); $decoded = base64_decode($exploded[1]); $image = Image::make($decoded); // 调整图像大小,最长边不超过500像素 $image->resize(500, null, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); // 根据原始图像格式设置文件扩展名 if (Str::contains($exploded[0], 'jpeg')) { $extension = 'jpg'; } else { $extension = 'png'; } $fileName = Str::random() . '.' . $extension; $path = public_path() . '/images/products/' . $fileName; $image->save($path); return '/images/products/' . $fileName; }
https://github.com/Intervention/image
希望对你有所帮助。
英文:
You can try the Intervention Image package in Laravel to resize before uploading.
-
Install the package:
composer require intervention/image
-
Add the below code at the beginning of your file to import the required classes:
use Intervention\Image\ImageManagerStatic as Image;
use Illuminate\Support\Str;
-
Modify the handleImage method like below:
private function handleImage($image) { $exploded = explode(',', $image); $decoded = base64_decode($exploded[1]); $image = Image::make($decoded); // Resize the image to a maximum size of 500px on the longest side $image->resize(500, null, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); // Set the file extension based on the original image format if (Str::contains($exploded[0], 'jpeg')) { $extension = 'jpg'; } else { $extension = 'png'; } $fileName = Str::random() . '.' . $extension; $path = public_path() . '/images/products/' . $fileName; $image->save($path); return '/images/products/' . $fileName; }
https://github.com/Intervention/image
Hope it may help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论