How to compress image before uploading in Laravel?

32,306

Solution 1

You need to optimize the image for web usage as user may upload images that are way to large (Either in size or resolution). You may also want to remove the meta data from the images to decrease the size even more. Intervention Image perfect for resizing/optimizing images for web usage in Laravel. You need to optimize the image before it is saved so that the optimized version is used when loading the web page.

Intervention Image

Solution 2

The best and easiest way to compress images before uploading to the server, I found here:-

https://github.com/spatie/laravel-image-optimizer

Solution 3

https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.

$filepath = public_path('storage/profile_images/'.$filename); 
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);

Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel

Share:
32,306
ÛmÄîr MÄlîk
Author by

ÛmÄîr MÄlîk

Results-oriented and innovative Senior Software Engineer with 5+ years of experience. Easily communicates complex technical requirements to non-technical stakeholders. Excellent leadership record of leading development teams in enterprise-wide development projects. Proficient in Agile/SCRUM methodology.

Updated on September 28, 2021

Comments

  • ÛmÄîr MÄlîk
    ÛmÄîr MÄlîk over 2 years

    I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:

    $rules = array('file' => 'required');
    $destinationPath = 'assets/images/pages'
    $validator = Validator::make(array('file' => $file), $rules);
    if ($validator->passes()) {
       $filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
       $file->move($destinationPath, $filename);
       return $filename;
    } else {
       return '';
    }