使用PHP缩放图像并保持纵横比

前端之家收集整理的这篇文章主要介绍了使用PHP缩放图像并保持纵横比前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上,我想上传一个图像(我已经排序),并将其缩放到某些约束,如最大宽度和高度,但是保持原始图像的宽高比.

我没有在服务器上安装Imagick – 否则这将很容易.

任何帮助一如以往的赞赏.
谢谢.

编辑:我不需要整个代码或任何东西,只是推动正确的方向将是太棒了.

我已经写了一个这样的代码,用于另一个我完成的项目.我下面复制了它,可能需要一点修补! (它需要GD库)

这些是它需要的参数:

$image_name - Name of the image which is uploaded
$new_width - Width of the resized photo (maximum)
$new_height - Height of the resized photo (maximum)
$uploadDir - Directory of the original image
$moveToDir - Directory to save the resized image

它会将图像缩小或缩小到最大宽度或高度

function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir)
{
    $path = $uploadDir . '/' . $image_name;

    $mime = getimagesize($path);

    if($mime['mime']=='image/png') { 
        $src_img = imagecreatefrompng($path);
    }
    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
        $src_img = imagecreatefromjpeg($path);
    }   

    $old_x          =   imageSX($src_img);
    $old_y          =   imageSY($src_img);

    if($old_x > $old_y) 
    {
        $thumb_w    =   $new_width;
        $thumb_h    =   $old_y*($new_height/$old_x);
    }

    if($old_x < $old_y) 
    {
        $thumb_w    =   $old_x*($new_width/$old_y);
        $thumb_h    =   $new_height;
    }

    if($old_x == $old_y) 
    {
        $thumb_w    =   $new_width;
        $thumb_h    =   $new_height;
    }

    $dst_img        =   ImageCreateTrueColor($thumb_w,$thumb_h);

    imagecopyresampled($dst_img,$src_img,$thumb_w,$thumb_h,$old_x,$old_y); 


    // New save location
    $new_thumb_loc = $moveToDir . $image_name;

    if($mime['mime']=='image/png') {
        $result = imagepng($dst_img,$new_thumb_loc,8);
    }
    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
        $result = imagejpeg($dst_img,80);
    }

    imagedestroy($dst_img); 
    imagedestroy($src_img);

    return $result;
}
原文链接:https://www.f2er.com/php/131474.html

猜你在找的PHP相关文章