如何裁剪图像而不是用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。反对种植。
答案 0 :(得分:-2)
请尝试使用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
变量设置值。