我正在使用php脚本上传和调整图片大小,非常简单:
if($_SERVER["REQUEST_METHOD"] == "POST") {
$image = $_FILES["image_upload"];
$uploadedfile = $image['tmp_name'];
if ($image) {
$filename = stripslashes($_FILES['image_upload']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
$error_txt = 'Immagine incoretta';
$errors=1;
} else {
$size=filesize($uploadedfile);
if ($size > MAX_SIZE*1024) {
$error_txt = "Immagine troppo grande";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ) {
$uploadedfile = $uploadedfile;
$src = imagecreatefromjpeg($uploadedfile);
} else if($extension=="png") {
$uploadedfile = $uploadedfile;
$src = imagecreatefrompng($uploadedfile);
} else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=500;
$newheight=375;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "images/". generateRandomString(5) . $image['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
}
}
我想要更进一步,现在我只是调整图像的大小,无论比例如何,我认为,我希望将其调整到固定的高度和高度而不会失去原始比例,这当然是实现的通过裁剪+调整原始图像的大小。
我不知道如何使用我的实际 imagecreatetruecolor 和 imagecopyresampled 函数来执行此操作,并且查看php手册似乎不是很容易。
有一个非常good library我试图集成到我的代码中,使用它就像 mysite.com/lib/timthumb.php?src=castle1.jpg&h=180&w一样简单= 120 但我不知道如何将其与我的实际代码集成。
那么,你有什么建议?
答案 0 :(得分:2)
如果以下代码中有任何拼写错误或任何内容,请原谅我。我没有测试过。我在这里做的是计算高度或宽度是否是太长的比例。然后调整源尺寸以匹配最终图像尺寸。另外,调整我们缩小的边的中心,使裁剪的图像居中。
$newwidth = 500;
$newheight = 375;
$tmp = imagecreatetruecolor($newwidth, $newheight);
$widthProportion = $width / $newwidth;
$heightProportion = $height / $newheight;
if ($widthProportion > $heightProportion) {
// width proportion is greater than height proportion
// figure out adjustment we need to make to width
$widthAdjustment = ($width * ($widthProportion - $heightProportion));
// Shrink width to proper proportion
$width = $width - $widthAdjustment;
$x = 0; // No adjusting height position
$y = $y + ($widthAdjustment / 2); // Center the adjustment
} else {
// height proportion is greater than width proportion
// figure out adjustment we need to make to width
$heightAdjustment = ($height * ($heightProportion - $widthProportion));
// Shrink height to proper proportion
$height = $height - $heightAdjustment;
$x = $x + ($heightAdjustment / 2); // Center the ajustment
$y = 0; // No adjusting width position
}
imagecopyresampled($tmp, $src, 0, 0, $x, $y, $newwidth, $newheight, $width, $height);
所以基本上使用$ width和$ height变量来指定你想要的图片数量(裁剪)。和$ x,$ y我们说的是我们想要裁剪图片的地方。其余的只是标准尺寸调整以适应全新的图像。
我希望有所帮助!