我有一个图像上传脚本,将上传的图像大小调整为150x150像素。如果图像是方形的,那很棒,但如果某人上传了一张640x200像素的图像,看起来不太好看。PHP图像调整大小 - 从中心平方/裁剪缩略图?
所以我基本上需要它自动创建一个基于图像中心的平方缩略图。如果图像较宽,则应裁剪左侧和右侧。如果图像较高,则应该裁剪顶部和底部。
我发现了一个代码修改网上,在这里要准确:
Upload, resize, and crop center of image with PHP
我不是伟大的PHP和我已经在这个现在几个小时,试图以我的代码合并下面有上面的选项。如果有人可以帮助我,这将是伟大的:)
$target_path = "avatars/";
$image = $_FILES['uploadedfile']['name'];
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
$_POST["userpic"]=$_FILES['uploadedfile']['name'];
if($_FILES['uploadedfile']['tmp_name']!="") {
$imagetype=explode(".",$_POST["userpic"]);
if($imagetype[1]=="jpg" || $imagetype[1]=="JPG" || $imagetype[1]=="gif" || $imagetype[1]=="GIF")
{
$target_path = "avatars/";
$thaid=$_POST["user_id"];
$target_path = $target_path .$thaid.".".$imagetype[1];
$target_path2 =$thaid.".".$imagetype[1];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
$_POST["userpic"]=$target_path2;
$n_width=$setts['avatar_width'];
$n_height=$setts['avatar_height'];
$tsrc=$target_path;
$add=$target_path;
if($imagetype[1]=="jpg" || $imagetype[1]=="JPG")
{
$im=imagecreatefromjpeg($add);
$width=imagesx($im);
$height=imagesy($im);
$newimage=imagecreatetruecolor($n_width,$n_height);
$ar = 1.00;
if ($ar < 1) { // "tall" crop
$cropWidth = min($height * $ar, $width);
$cropHeight = $cropWidth/$ar;
}
else { // "wide" crop
$cropHeight = min($width/$ar, $height);
$cropWidth = $cropHeight * $ar;
}
imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$cropWidth,$cropHeight);
imagejpeg($newimage,$tsrc,100);
}
if($imagetype[1]=="gif" || $imagetype[1]=="GIF")
{
$im=imagecreatefromgif($add);
$width=imagesx($im);
$height=imagesy($im);
$newimage=imagecreatetruecolor($n_width,$n_height);
imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
imagegif($newimage,$tsrc,100);
}
}
else
{
$_POST["userpic"]="noimage.jpg";
}
}
非常感谢!我设法编辑了这个脚本,这是工作,除了它从左侧裁剪图像,而不是居中。任何想法我失踪? – user1227914 2012-02-23 12:08:47
非常感谢!我设法编辑了这个脚本,这是工作,除了它从左侧裁剪图像,而不是居中。任何想法我失踪? – user1227914 2012-02-23 12:08:47
(我编辑了上面的源代码) – user1227914 2012-02-23 12:09:40