Php 调整宽度修复


Php resize width fix

我在PHP中有这个函数。

<?php
function zmensi_obrazok($max_dimension, $image_max_width, $image_max_height, $dir, $obrazok, $obrazok_tmp, $obrazok_size, $filename){

$postvars          = array(
"image"            => $obrazok,
"image_tmp"        => $obrazok_tmp,
"image_size"       => $obrazok_size,
"image_max_width"  => $image_max_width,
"image_max_height" => $image_max_height
);
// Array of valid extensions.
$valid_exts = array("jpg","jpeg","gif","png");
// Select the extension from the file.
$ext = end(explode(".",strtolower($obrazok)));
// Check not larger than 175kb.
if($postvars["image_size"] <= 256000){
// Check is valid extension.
if(in_array($ext,$valid_exts)){
if($ext == "jpg" || $ext == "jpeg"){
$image = imagecreatefromjpeg($postvars["image_tmp"]);
}
else if($ext == "gif"){
$image = imagecreatefromgif($postvars["image_tmp"]);
}
else if($ext == "png"){
$image = imagecreatefrompng($postvars["image_tmp"]);
}
list($width,$height) = getimagesize($postvars["image_tmp"]);
if($postvars["image_max_width"] > $postvars["image_max_height"]){
    if($postvars["image_max_width"] > $max_dimension){
            $newwidth = $max_dimension;
        } 
        else 
        {
            $newwidth = $postvars["image_max_width"];
        }
}
else
{
    if($postvars["image_max_height"] > $max_dimension)
    {
        $newheight = $max_dimension;
    }
        else
        {
            $newheight = $postvars["image_max_height"];
        }

}
$tmp = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($tmp,$filename,100);
return "fix";
imagedestroy($image);
imagedestroy($tmp);
}
}
}
?>

现在,如果我想使用它,并且我上传图像,例如 500x300 像素,并且我将最大尺寸设置为 205x205 像素,它不想使调整大小的图片比例。它看起来像375x205(高度还可以)。有人可以帮忙解决吗?

只需缩放图像两次,一次以匹配宽度,一次以匹配高度。为了节省处理时间,请先进行缩放,然后调整大小:

$max_w = 205;
$max_h = 205;
$img_w = ...;
$img_h = ...;
if ($img_w > $max_w) {
    $img_h = $img_h * $max_w / $img_w;
    $img_w = $max_w;
}
if ($img_h > $max_h) {
    $img_w = $img_w * $max_h / $img_h;
    $img_h = $max_h;
}
// $img_w and $img_h should now have your scaled down image complying with both restrictions.