首頁  >  問答  >  主體

在 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 天前511

全部回覆(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
  • 取消回覆