Php resize width fix

只谈情不闲聊 提交于 2020-01-15 12:29:09

问题


I have this function in 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);
}

}

}

?>

Now if I want to use it, and I upload image for example 500x300px and I have set max size to 205x205px it don't want to make resized picture proportion. It make something like 375x205 (height is still OK). Can somebody help how to fix it?


回答1:


Just scale your image twice, once to match the width, once to match the height. To save on processing, get your scaling first, then do the resizing:

$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.


来源:https://stackoverflow.com/questions/11273051/php-resize-width-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!