Compressing image spacing Laravel
I have a script that saves and caches intrusive images and it works 100%
However, I'm trying to figure out how I can add 75% compression to jpg and png files, but I don't know what would apply it in this situation.
I didn't think PNG files could be compressed separately from the software that does it, so I'm not sure if they are the same thing?
Here's an example of compression: http://image.intervention.io/api/save
/* ////////////////////// IMAGES //////////////////////// */
Route::get( '/media/{size}/{crop}/{name}', function ( $size = null, $crop = null, $name = null ) {
if ( ! is_null( $size ) and ! is_null( $name ) and ! is_null( $crop ) ) {
$size = explode( 'x', $size );
$hours = 48;
$cache_length = $hours * 60;
switch ( $crop ) {
/*///////////////////////// no crop and change ratio */
case "0":
$cache_image = Image::cache( function ( $image ) use ( $size, $name ) {
return $image->make( url( '/uploads/' . $name ) )->resize( $size[0], $size[1] )->sharpen(5);
}, $cache_length);
break;
/*///////////////////////// crop - NO upsize */
default:
case "1":
$cache_image = Image::cache( function ( $image ) use ( $size, $name ) {
return $image->make( url( '/uploads/' . $name ) )->fit( $size[0], $size[1], function ( $constraint ) {
$constraint->upsize();
} )->sharpen(5);
}, $cache_length );
break;
/*///////////////////////// crop - WITH upsize */
case "2":
$cache_image = Image::cache( function ( $image ) use ( $size, $name ) {
return $image->make( url( '/uploads/' . $name ) )->fit( $size[0], $size[1], function ( $constraint ) {
//$constraint->upsize();
} )->sharpen(5);
}, $cache_length );
break;
/*///////////////////////// No crop & add borders */
case "3":
$cache_image = Image::cache( function ( $image ) use ( $size, $name ) {
$image->make( url( '/uploads/' . $name ) )->resize( $size[0], $size[1], function ( $constraint ) {
$constraint->aspectRatio();
$constraint->upsize();
} )->sharpen(5);
$image->resizeCanvas($size[0], $size[1], 'center', false, array(255, 255, 255, 0.0));
return $image;
}, $cache_length );
break;
/*///////////////////////// No crop */
case "4":
$cache_image = Image::cache( function ( $image ) use ( $size, $name ) {
$image->make( url( '/uploads/' . $name ) )->resize( $size[0], $size[1], function ( $constraint ) {
$constraint->aspectRatio();
$constraint->upsize();
} )->sharpen(5);
//$image->resizeCanvas($size[0], $size[1], 'center', false, array(255, 255, 255, 0.0));
return $image;
}, $cache_length );
break;
}
return Response::make( $cache_image, 200, [ 'Content-Type' => 'image' ] )->setMaxAge(604800)->setPublic();
} else {
abort( 404 );
}
} );
+3
source to share
1 answer
Try a method encode()
where you can specify format
and quality
(for jpg
). So, every time you use the cache try this:
$cache_image = Image::cache(function ($image) use ($size, $name) {
$image
->make(...)
->... // any other call to image manipulation methods
->encode('jpg', 75);
// ...
return $image;
});
+2
source to share