Skip to content

Instantly share code, notes, and snippets.

@webdawe
Created September 20, 2016 04:56
Show Gist options
  • Save webdawe/dd25c59b30cd98eff30a1db043b4c9e7 to your computer and use it in GitHub Desktop.
Save webdawe/dd25c59b30cd98eff30a1db043b4c9e7 to your computer and use it in GitHub Desktop.
GD Library Resize PHP
function gdResize($uploadDir, $filename,$ext, $newWidth, $newHeight)
{
list($orginalWidth, $orginalHeight) = getimagesize($uploadDir. $filename . '.' . $ext);
$ratio = $orginalWidth/$orginalHeight;
if ($orginalWidth < $newWidth || $orginalHeight < $newHeight)
{
return '';
}
else if ($newWidth/$newHeight > $ratio)
{
$newWidth = $newHeight * $ratio;
}
else
{
$newHeight = $newWidth / $ratio;
}
$thumb = imagecreatetruecolor($newWidth, $newHeight);
$sourceFile = $uploadDir. $filename . '.'. $ext;
switch ($ext)
{
case 'jpg':
$source = imagecreatefromjpeg($sourceFile);
break;
case 'gif' :
$source = imagecreatefromgif($sourceFile);
break;
case 'png' :
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$transparency = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
imagefilledrectangle($thumb, 0, 0, $newWidth, $newHeight, $transparency);
$source = imagecreatefrompng($sourceFile);
break;
case 'bmp' :
$source = imagecreatefromwbmp($sourceFile);
break;
}
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $orginalWidth, $orginalHeight);
$thumbnailFile = 'thumb_' . $filename . '.' . $ext;
switch ($ext)
{
case 'jpg':
imagejpeg($thumb, $uploadDir .$thumbnailFile, 0);
break;
case 'gif' :
imagegif($thumb, $uploadDir .$thumbnailFile, 0);
break;
case 'png' :
imagepng($thumb, $uploadDir .$thumbnailFile, 0);
break;
case 'bmp' :
imagewbmp($thumb, $uploadDir .$thumbnailFile, 0);
break;
}
return $thumbnailFile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment