8

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 '';
}
ÛmÄîr MÄlîk
  • 453
  • 2
  • 10
  • 23
  • I think most webservers and webbrowsers support gzipping of content out of the box so you shouldn't really need to do anything for lossless compression. Of course this only affects the server > client direction. – apokryfos Feb 23 '17 at 09:06
  • @apokryfos I've enabled gzipping using htaccess and page insight of also tell me that compression is enabled but still it's giving me error to reduce image size and my page speed is just between 20-28. – ÛmÄîr MÄlîk Feb 23 '17 at 09:11
  • You can resize the image using image intervention and store both - the resized and original version. the resized version should have the dimensions you will display them later - therfore you won't see a quality loss. If you still require originals you will also have them in place this way – Frnak Feb 23 '17 at 09:19

4 Answers4

9

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

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

Pawan Verma
  • 1,152
  • 14
  • 22
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Johan Jul 20 '19 at 14:15
6

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

TedRed
  • 377
  • 2
  • 5
  • I tried to integrate it in Laravel but running following composer command but it gives error that: php composer.phar require intervention/image Could not open input file: composer.phar : php composer.phar require intervention/image – ÛmÄîr MÄlîk Feb 23 '17 at 09:59
  • Are you running the command in your laravel project directory? – TedRed Feb 23 '17 at 10:23
  • yes. I followed this blog after that and now composer updated successfully. http://devartisans.com/articles/resize-images-laravel5.1 I want to know should I've to run following artisan command: php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5" – ÛmÄîr MÄlîk Feb 23 '17 at 10:38
  • you need to run that command only when you want to change the config, i.e change the driver from GD (default) into Imagick – Bang Fady Jan 20 '19 at 07:12
  • @ÛmÄîrMÄlîk Suggesting you to try below command:- composer require intervention/image – Pawan Verma Jul 29 '22 at 06:16
2

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

  • First install library by running the command 'composer require tinify/tinify' in your Laravel project. And then try the above code . – Sajid Sayyad Jul 07 '17 at 06:26
0

**Using core php **


    function compress($source_image, $compress_image)
    {
        $image_info = getimagesize($source_image);
        if ($image_info['mime'] == 'image/jpeg') {
            $source_image = imagecreatefromjpeg($source_image);
            imagejpeg($source_image, $compress_image, 20);             //for jpeg or gif, it should be 0-100
        } elseif ($image_info['mime'] == 'image/png') {
            $source_image = imagecreatefrompng($source_image);
            imagepng($source_image, $compress_image, 3);
        }
        return $compress_image;
    }
    public function store(Request $request)
    {
        $image_name = $_FILES['image']['name'];
        $tmp_name = $_FILES['image']['tmp_name'];

        $directory_name = public_path('/upload/image/');
        $file_name = $directory_name . $image_name;
        move_uploaded_file($tmp_name, $file_name);

        $compress_file = "compress_" . $image_name;
        $compressed_img = $directory_name . $compress_file;
        $compress_image = $this->compress($file_name, $compressed_img);
        unlink($file_name);
    }

Subhash
  • 1
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 27 '21 at 10:05