Reputation: 473
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 '';
}
Upvotes: 10
Views: 58885
Reputation: 1
**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); }
Upvotes: 0
Reputation: 37
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
Upvotes: 2
Reputation: 427
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.
Upvotes: 7