GD调整图像大小和裁剪边缘

时间:2013-08-25 00:38:44

标签: php gd

基本上如果我有一个3400x3400的图像并且我的目标尺寸是340x200,那么我想从原始图像的中间抓取相应的3400x2000,然后将其缩小到340x200,我对它的外观有一个大概的了解,这是我到目前为止:

$RealWidth=164;
$RealHeight=126;
$org_img = imagecreatefromjpeg($newname);    
list($width, $height) = getimagesize($newname);
$ratio2 = $height/$width;
$ratio = $RealHeight/$RealWidth;
$img = imagecreatetruecolor($RealWidth,$RealHeight);
$ims = getimagesize($newname);
imagecopyresized($img,$org_img, 0, 0, 0, 0, $RealWidth, $RealHeight, $height*$ratio2, $height);
imagejpeg($img,$newname,90);
imagedestroy($img);

我对数学有点困惑,我也希望它能够在需要时从顶部/底部裁剪区域。

1 个答案:

答案 0 :(得分:0)

您的代码中插入了“新”数学:

$RealWidth=164;
$RealHeight=126;
$org_img = imagecreatefromjpeg($newname);
list($width, $height) = getimagesize($newname);
$ratio = $width / $height < $RealWidth / $RealHeight ? $RealWidth / $width : $RealHeight / $height;
$src_x = round($width  / 2 - ($RealWidth  / 2) / $ratio);
$src_y = round($height / 2 - ($RealHeight / 2) / $ratio);
$src_w = round($RealWidth  / $ratio);
$src_h = round($RealHeight / $ratio);
$img = imagecreatetruecolor($RealWidth,$RealHeight);
$ims = getimagesize($newname);
imagecopyresized($img, $org_img, 0, 0, $src_x, $src_y, $RealWidth, $RealHeight, $src_w, $src_h);
imagejpeg($img,$newname,90);
imagedestroy($img);