简体   繁体   中英

Php | Crop Image Without Stretching

How can I have images cropped instead of stretched with Php?

For instance, if I upload a 600, 100 image, I want it to crop it to 100x100, in the CENTER of the image. So 250px from the left. Obviously these numbers would depend on the image the user uploads.

Here is my current code :

$width = imagesx($base64);
$height = imagesy($base64);

$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $base64,
    0, 0,
    0, 0,
    $newWidth, $newHeight,
    $width, $height);

imagejpeg($tmp, $path)

If I am not mistaken, this code would take a 600x100 image and stretch it down to a 100x100. Opposed to cropping.

Please try to use this code :

$new = imagecreatefromjpeg($uploadedfile);

$crop_width = imagesx($new);
$crop_height = imagesy($new);

$size = min($crop_width, $crop_height);

if($crop_width >= $crop_height) {
    $newx= ($crop_width-$crop_height)/2;
    $im2 = imagecrop($new, ['x' => $newx, 'y' => 0, 'width' => $size, 'height' => $size]);
}
else {
    $newy= ($crop_height-$crop_width)/2;
    $im2 = imagecrop($new, ['x' => 0, 'y' => $newy, 'width' => $size, 'height' => $size]);
}

imagejpeg($im2,$filename,90);

You need to set your values for $uploadedfile , $crop_width , $crop_height and $filename variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM