Using Intervention package to compress images. My

2019-07-22 14:59发布

问题:

I'm using this package http://image.intervention.io/getting_started/installation to compress my images that's uploaded to my server. However the images are not being compressed.

  1. First I installed the Intervention package by putting this in my terminal:

    composer require intervention/image

  2. Then I added this at the top of my controller:

    use Intervention\Image\ImageManagerStatic as Image;

  3. Then I added the encode to minify the image

    Image::make(request()->file('img'))->encode('jpg', 1);

  4. It's not minifying the image. It's still the same size.

    <?php
    
    namespace App\Http\Controllers;
    
    use Intervention\Image\ImageManagerStatic as Image;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\Request;
    
    class UploadsController extends Controller
    {
    
        public function store()
        {
    
            // Get image
            $img = request()->file('img');
    
            // Minify image
            Image::make($img)->encode('jpg', 1);
    
            // Store image in uploads folder
            Storage::disk('public')->put('uploads', $img);
    
        }
    
    }
    

回答1:

It's simple:

Quality is only applied if you're encoding JPG format since PNG compression is lossless and does not affect image quality. Default: 90.

Use jpg if you want this library to compress your images.



回答2:

Looks like you are just saving the original image and not the resized version. You could try something like this:

public function store()
{

    // Get image
    $img = request()->file('img');

    // Minify image
    $resizedImage = Image::make($img)->encode('jpg', 1); // put this in a variable

   // use a unique filename
   $filename = $img->hashName()

    // Store image in uploads folder
    Storage::disk('public')->put('uploads/'.$filename, $resizedImage->__toString());

}