PHP实现图片裁剪
原创
52cxy
11-25 08:53
阅读数:469
PHP实现图片裁剪:
/**
* 图像裁剪
* @param $src string 原图路径
* @param $dst string 裁剪图片路径
* @param $dstW int 需要裁剪的宽
* @param $dstH int 需要裁剪的高
*/
function imagecropper($src, $dst, $dstW, $dstH)
{
list($srcWidth, $srcHeight, $type) = getimagesize($src);
$sourceRatio = $srcHeight / $srcWidth;
$targetRatio = $dstH / $dstW;
if ($sourceRatio > $targetRatio)
{
$croppedW = $srcWidth;
$croppedH = $srcWidth * $targetRatio;
$sourceX = 0;
$sourceY = ($srcHeight - $croppedH) / 2;
}
elseif ($sourceRatio < $targetRatio)
{
$croppedW = $srcHeight / $targetRatio;
$croppedH = $srcHeight;
$sourceX = ($srcWidth - $croppedW) / 2;
$sourceY = 0;
}
else
{
$croppedW = $srcWidth;
$croppedH = $srcHeight;
$sourceX = 0;
$sourceY = 0;
}
if($type == 1) $sourceImage = imagecreatefromgif($src);
elseif($type == 2) $sourceImage = imagecreatefromjpeg($src);
elseif($type == 3) $sourceImage = imagecreatefrompng($src);
$targetImage = imagecreatetruecolor($dstW, $dstH);
$croppedImage = imagecreatetruecolor($croppedW, $croppedH);
imagecopy($croppedImage, $sourceImage, 0, 0, $sourceX, $sourceY, $croppedW, $croppedH);//裁剪
imagecopyresampled($targetImage, $croppedImage, 0, 0, 0, 0, $dstW, $dstH, $croppedW, $croppedH);//缩放
imagepng($targetImage, $dst);
imagedestroy($targetImage);
}测试代码:
imagecropper('sample.jpg', "last.jpg", 200, 100);共0条评论