Skip to content

Instantly share code, notes, and snippets.

@psdtohtml5
Created July 11, 2013 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psdtohtml5/5974960 to your computer and use it in GitHub Desktop.
Save psdtohtml5/5974960 to your computer and use it in GitHub Desktop.
PHP : Dynamic Image Resize
<?php
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function resizeImage($imgSrc,$thumbnail_width,$thumbnail_height, $extension) { //$imgSrc is a FILE - Returns an image resource.
//getting the image dimensions
list($width_orig, $height_orig) = getimagesize($imgSrc);
if($extension == "jpg" || $extension =="jpeg"){
$myImage = imagecreatefromjpeg($imgSrc);
} elseif ($extension == "png") {
$myImage = imagecreatefrompng($imgSrc);
} else{
$myImage = imagecreatefromgif($imgSrc);
}
$ratio_orig = $width_orig/$height_orig;
if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
$new_height = $thumbnail_width/$ratio_orig;
$new_width = $thumbnail_width;
} else {
$new_width = $thumbnail_height*$ratio_orig;
$new_height = $thumbnail_height;
}
$x_mid = $new_width/2; //horizontal middle
$y_mid = $new_height/2; //vertical middle
$process = imagecreatetruecolor(round($new_width), round($new_height));
//if($extension == "jpg" || $extension =="jpeg") {
imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
$thumb = imagecreatetruecolor($thumbnail_width, $new_height);
imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), 0, $thumbnail_width, $new_height, $thumbnail_width, $new_height);
imagedestroy($process);
imagedestroy($myImage);
return $thumb;
}
$image = $_Post['image']['name'];
$extension = getExtension($image);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension == "jpg") || ($extension == "jpeg") || ($extension == "png") || ($extension = "gif"))
{
$temp= resizeImage($_Post['image']['tmp_name'], 585,330, $extension);
$path_parts = pathinfo($image);
$fileImage = $path_parts['filename'];
$imgfile= 'images/'.$fileImage.'.jpg';
imagejpeg ( $temp, $imgfile );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment