在 PHP (GD) 中调整缩略图大小后纵横比不同


Aspect ratio not same after resizing thumbnails in PHP (GD)

我正在调整图像大小以在PHP中制作缩略图,但纵横比不同。我已经离开了代码,但我无法弄清楚问题是什么。这是我正在使用的代码。

<?php
$idir = "gallery/";
$tdir="gallery/thumbs/";
if(!file_exists($tdir)){
mkdir($tdir);
}
chmod($idir,755); 

/* It creates new thumbnails here */
function createThumbs($idir, $tdir, $tw, $th){
$dir=opendir($idir);
global $fname;
while(($fname = readdir($dir)) != false){
if($fname!='.' && $fname != '..'){
$img = imagecreatefromjpeg($idir.$fname);
$width = imagesx($img);
$height = imagesy($img);
if($width>$height){
$nw=$tw;
$nh=$height*($th/$width);
}
if ($width < $height) 
{
$nw=$width*($tw/$height);
$nh=$th;
}
if ($width == $height) 
{
$nw=$tw;
$nh=$th;
}
$tmp_img = imagecreatetruecolor($nw, $nh);
imagecopyresampled($tmp_img, $img, 0,0,0,0, $nw, $nh, $width, $height);
imagejpeg($tmp_img, $tdir.'tn_'.$fname);
}
}
closedir($dir);
}
if (!file_exists($tdir.'tn_'.$fname)) {
createThumbs($idir,$tdir,903, 603);
}
?>

请帮我找出问题所在。

另外,请分享任何其他在 php 中创建缩略图的有效方法。

尝试使用 imagecopyresampled() 而不是 imagecopyressize()。

我发现我做错了什么。计算新纵横比的公式是错误的,新公式将是这样的:

if($width>$height){
            $nw=$tw;
            $nh=$height*($tw/$width);
        }
        if ($width < $height) 
        {
            $nw=$width*($th/$height);
            $nh=$th;
        }
        if ($width == $height) 
        {
            $nw=$tw;
            $nh=$th;
        }