Optimize Image Automatically On The Fly In Laravel

by pure luck i stumbled upon a package call laravel-image-optimizer and a quick look to the usage it seems very easy to use

public function store(Request $request, ImageOptimizer $imageOptimizer)
{
  $picture = $request->file('picture');

  // optimize
  $imageOptimizer->optimizeUploadedImageFile($picture);

  // save
  Storage::put('/my/cool/path/test.jpg', File::get($picture));
}

but i thought why not instead of writing that one liner, we use a middleware to automate the images optimization & so your workflow remain the same and you get a 20%-70% smaller images.

so i made the PR and it was accepted HORRAAAY. 👏💪💃

# How to Use the Package ?

1- install the package
2- register the service provider
3- install the optimization libraries
4- add the middleware ‘AutoImageOptimizer’ to the route you want, or just add it to the web $middlewareGroups under App\Http\Kernel.php

protected $middlewareGroups = [
  'web' => [
    // ...

    'AutoImageOptimizer',
  ],
];

as the middleware only intercepts the methods which are not GET & then check if there are any files in the request b4 do anything, imho its safe to keep it in there.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s