【问题标题】:Php | Crop Image Without Stretchingphp |裁剪图像而不拉伸
【发布时间】:2017-10-29 12:35:00
【问题描述】:

如何使用 Php 裁剪而不是拉伸图像?

例如,如果我上传一张 600、100 的图片,我希望它在图片的中心将其裁剪为 100x100。所以从左边250px。 显然,这些数字将取决于用户上传的图像。

这是我当前的代码:

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

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

imagejpeg($tmp, $path)

如果我没记错的话,这段代码会采用 600x100 的图像并将其拉伸到 100x100。反对裁剪。

【问题讨论】:

    标签: php


    【解决方案1】:

    请尝试使用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);
    

    您需要为$uploadedfile$crop_width$crop_height$filename 变量设置值。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 2013-05-15
      • 2016-06-06
      • 2012-10-31
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2017-05-08
      • 2011-07-14
      相关资源
      最近更新 更多