1

我在 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);
}

}

}

?>

现在,如果我想使用它,并且我上传了例如 500x300px 的图像,并且我已将最大尺寸设置为 205x205px,它不想调整大小的图片比例。它制作类似 375x205 的东西(高度还可以)。有人可以帮助解决它吗?

4

1 回答 1

2

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

$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.
于 2012-06-30T09:37:17.933 回答