PHP Code To Resize and Crop Image
This function resize image and crop image. Here the Code:
// Function to resize image
function resizeImage($image,$width,$height,$scale) {
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromjpeg($image);
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$image,90);
chmod($image, 0777);
return $image;
}
// Function to crop image
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromjpeg($image);
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$thumb_image_name,90);
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
// Function to get image height
function getHeight($image) {
$sizes = getimagesize($image);
$height = $sizes[1];
return $height;
}
// Function to get image width
function getWidth($image) {
$sizes = getimagesize($image);
$width = $sizes[0];
return $width;
}
// Start to resize image
$large_image_location = "images/imagename.jpg"; // path to image
chmod($large_image_location, 0777);
$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
$max_width = "300"; // maximum image width, write your prefered
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
// Start to crop image
if (($height > $width) and ($width > 300)){
$x1 = 0;$y1 = 0;
$x2 = 300;$y2 = 250;
$w = 300;$h = 250;
$scale = 300/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
}
else if (($height > $width) and ($width < 300) and ($height > 250)){
$x1 = 0;$y1 = 0;
$x2 = $width;$y2 = 250;
$w = $width;$h = 250;
$scale = $width/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
}
else if (($height > $width) and ($width < 300) and ($height < 250)){
$x1 = 0;$y1 = 0;
$x2 = $width;$y2 = $height;
$w = $width;$h = $height;
$scale = $width/$w;
$cropped = resizeThumbnailImage($large_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
}
Good Luck !!!