Skip to content

Instantly share code, notes, and snippets.

@Ahed91
Created December 28, 2017 11:01
Show Gist options
  • Save Ahed91/0d8c068cb58dca4799bf3696a781cf10 to your computer and use it in GitHub Desktop.
Save Ahed91/0d8c068cb58dca4799bf3696a781cf10 to your computer and use it in GitHub Desktop.
image resizer php with crop and auto padding
<?php
// TODO create uploads/cache folder
public static function resize($path, $w, $h)
{
$path = ltrim($path, '/');
if (!file_exists(public_path($path))) {
$path = "uploads/placeholder.png";
}
$pos = strrpos($path, '.');
if ($pos === false) {
return $path;
}
$ext = substr($path, $pos);
$suffix = '_' . $w . '_' . $h . $ext;
$path_cache = str_replace($ext, '', $path);
$path_cache = str_replace('uploads', 'uploads/cache', $path_cache) . $suffix;
if (file_exists($path_cache)) {
return $path_cache;
}
$full_path = public_path($path);
$full_path_cache = public_path($path_cache);
$image = '';
$image_type = '';
// get image info about this file
$image_info = getimagesize($full_path);
// load file depending on mimetype
try {
switch ($image_info["mime"]) {
case "image/gif" :
$image_type = 'gif';
$image = @imagecreatefromgif($full_path);
break;
case "image/jpeg" :
$image_type = 'jpg';
$image = @imagecreatefromjpeg($full_path);
break;
case "image/png" :
$image_type = 'png';
$image = @imagecreatefrompng($full_path);
break;
}
} catch (Exception $e) {
Log::error('Exception loading ' . $full_path . ' - ' . $e->getMessage());
$path = "uploads/placeholder.png";
return $path;
}
// calc new dimensions
$image_width = imageSX($image);
$image_height = imageSY($image);
if ($image_width > $w || $image_height > $h) {
if (($image_width / $image_height) > ($w / $h)) {
$tnw = $w;
$tnh = $tnw * $image_height / $image_width;
} else {
$tnh = $h;
$tnw = $tnh * $image_width / $image_height;
}
} else {
$tnw = $image_width;
$tnh = $image_height;
}
// create a temp based on new dimensions
$tx = $w;
$ty = $h;
$px = ($w - $tnw) / 2;
$py = ($h - $tnh) / 2;
$temp_image = imagecreatetruecolor($tx, $ty);
// if padding, fill background
if ($image_type == 'png') {
imagealphablending($temp_image, false);
imagesavealpha($temp_image, true);
$color = imagecolorallocatealpha($temp_image, 0, 0, 0, 127);
imagefilledrectangle($temp_image, 0, 0, $tx, $ty, $color);
} else {
$col = [255, 255, 255];
$bg = imagecolorallocate($temp_image, $col[0], $col[1], $col[2]);
imagefilledrectangle($temp_image, 0, 0, $tx, $ty, $bg);
}
// copy resized
imagecopyresampled($temp_image, $image, $px, $py, 0, 0, $tnw, $tnh, $image_width,
$image_height);
switch ($image_type) {
case "gif" :
imagegif($temp_image, $full_path_cache);
break;
case "jpg" :
imagejpeg($temp_image, $full_path_cache, 75);
break;
case "png" :
imagepng($temp_image, $full_path_cache);
break;
}
return $path_cache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment