Last active
December 18, 2021 19:56
-
-
Save marifuli/5587e017dd065f4ed9d7616cb31eb122 to your computer and use it in GitHub Desktop.
Helper function for Image resizing in PHP, especially in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dynamic_image($url, $width = false, $height = -1, $quality = 80, $compression = 75) | |
{ | |
$parsed = parse_url($url); | |
$path = $parsed['path']; | |
$file_name = basename($path); | |
$only_path = str_replace($file_name, '', $path); | |
$public_path = public_path($path); | |
if(file_exists($public_path)) | |
{ | |
$content_type = explode('/', mime_content_type($public_path)); | |
$type = $content_type[1]; | |
if( | |
$content_type[0] == 'image' && | |
in_array($type, ['png', 'jpeg','jpg', 'gif', 'webp']) | |
) | |
{ | |
$cache_image_name = 'resized.cached_' ; | |
if($width !== false) | |
{ | |
$cache_image_name .= '_w_'. $width. '_'; | |
} | |
if($height !== false) | |
{ | |
$cache_image_name .= '_h_'. $height. '_'; | |
} | |
$cache_image_name .= '_quality_' . $quality . '_compression_' . $compression . $file_name; | |
$cache_image_path = public_path( | |
$only_path . $cache_image_name | |
); | |
if(!file_exists($cache_image_path)) | |
{ | |
$image = false; | |
//- create and save the image | |
if($type == 'png') | |
{ | |
$image = imagecreatefrompng($public_path); | |
imagepng($image, $cache_image_path); | |
} | |
if($type == 'jpg' || $type == 'jpeg') | |
{ | |
$image = imagecreatefromjpeg($public_path); | |
imagejpeg($image, $cache_image_path, $quality); | |
} | |
if($type == 'gif') | |
{ | |
$image = imagecreatefromgif($public_path); | |
imagegif($image, $cache_image_path); | |
} | |
if($type == 'webp') | |
{ | |
$image = imagecreatefromwebp($public_path); | |
imagewebp($image, $cache_image_path); | |
} | |
// dd(imagesx($image) > $width); | |
if($image && $width !== false && imagesx($image) > $width) | |
{ | |
$image = imagescale($image, $width, $height); | |
//- save the image again | |
if($type == 'png') | |
{ | |
imagepng($image, $cache_image_path); | |
} | |
if($type == 'jpg' || $type == 'jpeg') | |
{ | |
imagejpeg($image, $cache_image_path, $quality); | |
} | |
if($type == 'gif') | |
{ | |
imagegif($image, $cache_image_path); | |
} | |
if($type == 'webp') | |
{ | |
imagewebp($image, $cache_image_path); | |
} | |
} | |
return response()->file($cache_image_path); | |
} | |
return redirect(asset(str_replace($file_name, $cache_image_name, $url))); | |
} | |
} | |
return redirect($url); | |
//return 'file not found'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment