Skip to content

Instantly share code, notes, and snippets.

@davidbrooks
Created July 23, 2014 19:59
Show Gist options
  • Save davidbrooks/5d401e5463c0554027cf to your computer and use it in GitHub Desktop.
Save davidbrooks/5d401e5463c0554027cf to your computer and use it in GitHub Desktop.
A bulk image resizer, in PHP
<?php
$new_width = '640';
$uploadFolder = "images/";
$original_directory = $uploadFolder.'originals/';
// This first loop just moves anything missing over to the originals directory
foreach (glob($uploadFolder."*") as $filename) {
$file = explode($uploadFolder, $filename);
$file = $file[1];
$original_filename = $original_directory.''.$file;
if (file_exists($original_filename)) {
// This already exists over there,
} else {
rename($filename, $original_filename);
}
}
// Then we recreate all those images as smaller jpgs
foreach (glob($original_directory."*") as $o_filename) {
$img_info = getimagesize($o_filename);
$o_file = explode($original_directory, $o_filename);
$o_file = $o_file[1];
$width = $img_info[0];
$height = $img_info[1];
if ($height < $width) {
$ratio = $width / $height;
} else if ($width < $height) {
$ratio = $height / $width;
} else if ($width == $height) {
$ratio = 1;
}
$new_height = $new_width / $ratio;
$filetype = mime_content_type($o_filename);
switch($filetype) {
case 'image/jpeg':
case 'image/jpg':
$img = imagecreatefromjpeg($o_filename);
break;
case 'image/png':
$img = imagecreatefrompng($o_filename);
echo $o_filename;
break;
case 'image/gif':
$img = imagecreatefromgif($o_filename);
break;
}
$jpgname = explode('.', $o_file);
$jpgname_full = $jpgname[0] . '.jpg';
$new_image = $uploadFolder.''.$jpgname_full;
$tmp = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($tmp, $new_image, 100);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment