Answer the question
In order to leave comments, you need to log in
How to scale and crop an image using PHP?
Hello! I have a form in which any picture is uploaded for (roughly speaking) an avatar of an employee of an enterprise. You need to scale the image up to 100 pixels in one of the dimensions and then crop the excess in the other dimension. In short, the picture should be .jpg 100x100. It is done immediately on the fly... I put the first parameter simply $_FILES["image"]. Before that, I made the code myself, it turned out to be cut, but I could not figure out how to scale it and I spied on ready-made solutions on the Internet. It turned out here:
function prepare_e_photo($image, $save_to, $quality = 100) {
unlink($save_to);
$w = $_CONFIG["EMPLOYEES"]["IMAGE_W"];
$h = $_CONFIG["EMPLOYEES"]["IMAGE_H"];
list($width, $height) = getimagesize($image);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($image);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($dst, $save_to, $quality);
imagedestroy($src);
return $dst;
}
Answer the question
In order to leave comments, you need to log in
Wouldn't it be easier to use a PHP extension like GD2 , which is what it's designed for?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question