How to resize an Image in PHP
Images can be resized using ImageMagick or GD functions. If GD’s functions are used, the size of the image file is also reduced when raw digital camera images are sampled.
function image_resize($file_name, $width, $height, $crop=FALSE) {
list($wid, $ht) = getimagesize($file_name);
$r = $wid / $ht;
if ($crop) {
if ($wid > $ht) {
$wid = ceil($wid-($width*abs($r-$width/$height)));
} else {
$ht = ceil($ht-($ht*abs($r-$w/$h)));
}
$new_width = $width;
$new_height = $height;
} else {
if ($width/$height > $r) {
$new_width = $height*$r;
$new_height = $height;
} else {
$new_height = $width/$r;
$new_width = $width;
}
}
$source = imagecreatefromjpeg($file_name);
$dst = imagecreatetruecolor($new_width, $new_height);
image_copy_resampled($dst, $source, 0, 0, 0, 0, $new_width, $new_height, $wid, $ht);
return $dst;
}
$img_to_resize = image_resize(‘path-to-jpg-image’, 250, 250);
php resize image
// resize on upload
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
$target_filename = $file_name;
$ratio = $width/$height;
if( $ratio > 1) {
$new_width = $maxDim;
$new_height = $maxDim/$ratio;
} else {
$new_width = $maxDim*$ratio;
$new_height = $maxDim;
}
$src = imagecreatefromstring( file_get_contents( $file_name ) );
$dst = imagecreatetruecolor( $new_width, $new_height );
imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
imagedestroy( $src );
imagepng( $dst, $target_filename ); // adjust format as needed
imagedestroy( $dst );
}