Resizing Images With PHP
March 21st, 2010
This script resizes all of the image files in a directory which are larger than sizes prescribed in the script. It does so by looping through all of the files in the directory. First checking if files is an image files by its extension. Second if its width is greater than the $maxWidth or if its height is greater than $maxHeight. If it is an image and is too large a temp file, using the original files data, is created which is within the max size allowed and proportional to the original. The original is then deleted and the temp renamed to take its place.
<?php
$maxWidth = 800;
$maxHeight = 600;
$dir = ".";
$dh = opendir($dir);
while (false !== ($file = readdir($dh)))
{
$isResize = false;
$ext = isImageFile($file);
if($ext != false)
{
//creat image from filename
$img;
if($ext == "jpg" || $ext == "jpeg")
$img = imagecreatefromjpeg($file);
else if($ext == "gif")
$img = imagecreatefromgif($file);
else if($ext == "png")
$img = imagecreatefrompng($file);
$width = imagesx($img);
$height = imagesy($img);
//check if image needs to be resized
if($width > $maxWidth)
{
$isResize = true;
$scale = $maxWidth / $width;
$newHeight = $height * $scale;
$newWidth = $maxWidth;
}
if($height > $maxHeight)
{
$isResize = true;
$scale = $maxHeight / $height;
$newWidth = $width * $scale;
$newHeight = $maxHeight;
}
///resize if isResize is true
if($isResize)
{
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $img, 0,0,0,0, $newWidth, $newHeight, $width, $height);
if($ext == "jpg" || $ext == "jpeg")
{
imagejpeg($resizedImage, "tmp_" . $file);
}
else if($ext == "gif")
{
imagegif($resizedImage, "tmp_" . $file);
}
else if($ext == "png")
{
imagepng($resizedImage, "tmp_" . $file);
}
$fileName = $file;
unlink($file);
rename("tmp_" . $fileName, $fileName);
}
}
}
function isImageFile($file)
{
$split = explode(".",$file);
$last = count($split) - 1;
$ext = strtolower($split[$last]);
if($ext == "jpg" || $ext == "gif" || $ext == "png" || $ext == "jpeg")
return $ext;
else
return false;
}