首页  >  问答  >  正文

在 Laravel 5.8 中上传之前调整图像大小

<p>我有这个功能可以通过 Laravel 中的 api 上传图像:</p> <pre class="brush:php;toolbar:false;">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; }</pre> <p>如何在上传之前将图像调整为最大边长 500 像素的大小?</p>
P粉608647033P粉608647033384 天前508

全部回复(1)我来回复

  • P粉153503989

    P粉1535039892023-09-05 11:18:07

    您可以尝试使用 Laravel 中的 Intervention Image 包来调整大小,然后再上传。

    1. 安装软件包:

      作曲家需要干预/图像

    2. 在文件开头添加以下代码以导入所需的类:

      使用 Intervention\Image\ImageManagerStatic 作为图像;

      使用 Illuminate\Support\Str;

    3. 修改handleImage方法,如下所示:

      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

    希望对你有帮助

    回复
    0
  • 取消回复