PHP截取图像固定大小 取中间部分

由于在上一篇的代码中的贴出的代码的截取图像会存在不足,经过本人的经心测试 把截取的算法修改了 特别贴出来 ,欢迎大家转载

以下是代码:

<?php
function scaleImage4($x,$y,$x2,$y2)
{
	if($x/$y > $x2/$y2)
	{
		$r = $y/$y2;
		$x = ceil($x*($y2/$y));
		$y = $y2;
	}
	else
	{
		$r = $x/$x2;
		$y = ceil($y *($x2/$x));
		$x = $x2;
	}
	return array($x,$y);
}
function cropImage($srcPic,$width,$height)
{

	$w      = 0;    
	$x      = 0;    
	$y      = 0;    
	list($s_W, $s_H) = getimagesize($srcPic);	//得到原图的大小
	//echo "原图大小 w:$s_W H:$s_H </br>";
	list($newX,$newY)=scaleImage4($s_W,$s_H,$width,$height);	//根据原图的大小和要改变的大小计算出新的大小
	//echo "算出来的大小 w:$newX H:$newY </br>";
	//echo "要显示的大小 w:$width H:$height </br>";
	$image_p = imagecreatetruecolor($width,$height);//对图像进行载剪
	
	if($width/$height > $newX/$newY)
	{
		$x = ($newX-$width)/2;
		$y = 0;
	}
	else
	{
		$y=ceil(($newY-$height)/4);
		$x = 0;

	}	
	//echo "坐标 x:$x y:$y </br>";
	$image = imagecreatefromjpeg($srcPic);
	imagecopyresampled($image_p,$image,0,0,$x,$y,$width,$height,$s_W,$s_H);
	imagejpeg($image_p, null, 100);
	imagedestroy($image_p);
}
$filename= $_GET['filename'];
$width = $_GET['width'];
$height = $_GET['height'];
$path="http://www.zhfy.com"; //图片来源地址 "/"
$src = $path.$filename;
header('Content-type: image/jpeg');
echo cropImage($src,$width,$height);
// 输出的头信息

?>

 此代码可以直接在图片中请求 不在网站中生成图片,图片是中内存的中 ,如果您有其它需要请自行修改

使用方法:<img src="/thumbs.php?filename=111.jpg&width=110&height=250">';

原文地址:https://www.cnblogs.com/cms100/p/3280699.html