Created
December 6, 2016 06:09
-
-
Save tanftw/03890dbd81cc2188664fbd48fdf6eef4 to your computer and use it in GitHub Desktop.
Image Resizer
This file contains hidden or 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
<?php | |
class Image | |
{ | |
public static function resize($path, $new_width, $new_height) | |
{ | |
list($width, $height) = getimagesize($path); | |
if ($new_width > max( $width, $height ) && $new_height > max($width, $height)) | |
return; | |
$type = strtolower(substr(strrchr($path, "."), 1)); | |
$ratio = max( $width / $new_width, $height / $new_height ); | |
$new_width = $width / $ratio; | |
$new_height = $height / $ratio; | |
switch($type) { | |
case 'bmp': $src = imagecreatefromwbmp($path); break; | |
case 'gif': $src = imagecreatefromgif($path); break; | |
case 'jpg': $src = imagecreatefromjpeg($path); break; | |
case 'png': $src = imagecreatefrompng($path); break; | |
default : return "Unsupported picture type!"; | |
} | |
$dst = imagecreatetruecolor($new_width, $new_height); | |
// preserve transparency | |
if($type == "gif" or $type == "png"){ | |
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127)); | |
imagealphablending($dst, false); | |
imagesavealpha($dst, true); | |
} | |
imagecopyresampled($dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height); | |
switch($type) { | |
case 'bmp': imagewbmp($dst, $path); break; | |
case 'gif': imagegif($dst, $path); break; | |
case 'jpg': imagejpeg($dst, $path); break; | |
case 'png': imagepng($dst, $path, 9); break; | |
} | |
return true; | |
} | |
public static function resizeDirectory($directory, $new_width, $new_height) | |
{ | |
$images = glob($directory."*.{jpg,gif,png}", GLOB_BRACE); | |
foreach ($images as $image) { | |
Image::resize($image, $new_width, $new_height); | |
} | |
} | |
} | |
// Resize whole directory | |
$images_path = __DIR__ . '/path/to/directory/'; | |
Image::resizeDirectory($images_path, 220, 80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment