调整大小并裁剪/调整大小并与GD保持比例

时间:2013-12-31 01:21:33

标签: php image gd

我想创建一个php脚本来调整大小和/或创建图片缩略图。我搜索了一下,我发现了一个脚本,我修改了一点,它完美无缺。

问题是它会创建图片缩略图调整大小和裁剪图片。我希望能够在不裁剪的情况下调整图片大小,只调整大小并保持比例。我添加了一个变量$crop,当该变量为1时,我想要调整图片大小并进行裁剪,当它为0时只调整大小而不进行裁剪和比例相同。

这是功能

function resize_image($tmp_image, $type, $name, $width, $height, $crop, $upload_folder){

/* Get original image size */
list($tmp_width, $tmp_height) = getimagesize($tmp_image);


if($crop == 1)
{
/* Calculate new image size with ratio */
$ratio = max($width/$tmp_width, $height/$tmp_height);
$tmp_height = ceil($height / $ratio);
$x = ($tmp_width - $width / $ratio) / 2;
$tmp_width = ceil($width / $ratio);

/* New file name */
$path = $upload_folder.$name;

/* Read binary data from image file */
$img_string = file_get_contents($tmp_image);

/* Create image from string */
$image = imagecreatefromstring($img_string);

$tmp = imagecreatetruecolor($width, $height);

/* Keep transparency */
imagealphablending($tmp, false);
imagesavealpha($tmp, true);

imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$tmp_width, $tmp_height);

/* Save image */
if($type == 'image/jpeg')
{
    imagejpeg($tmp, $path, 100);
}
elseif($type == 'image/png')
{
    imagepng($tmp, $path, 9);
}
}
else
{
// no crop, resize but keep proportions
}

/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}

1 个答案:

答案 0 :(得分:0)

非常简单。如果高度大于宽度,则通过将新高度除以旧高度来获得比率,最后将宽度乘以比率以获得新宽度,如果宽度大于您执行相反的高度,例如以下示例代码:

就是这样,这是一个非常简单的算法。

if ($height > $width) 
{   
    $ratio = $maxheight / $height;  
    $newheight = $maxheight;
    $newwidth = $width * $ratio; 
}
else 
{
    $ratio = $maxwidth / $width;   
    $newwidth = $maxwidth;  
    $newheight = $height * $ratio;   
}