使用PHP缩放图像并保持纵横比 [英] Scale Image Using PHP and Maintaining Aspect Ratio

查看:233
本文介绍了使用PHP缩放图像并保持纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想上传一张图片(我已整理过)并将其缩小到某些约束,例如最大宽度和高度,但保持原始图像的宽高比。

Basically I want to upload an image (which i've sorted) and scale it down to certain constraints such as max width and height but maintain the aspect ratio of the original image.

我没有在服务器上安装Imagick - 否则这很容易。

I don't have Imagick installed on the server - otherwise this would be easy.

任何帮助都会一如既往地受到赞赏。
谢谢。

Any help is appreciated as always. Thanks.

编辑:我不需要整个代码或任何东西,只需向正确的方向推进就太棒了。

I don't need the whole code or anything, just a push in the right direction would be fantastic.

推荐答案

我为我做过的另一个项目编写了一段代码。我在下面复制了它,可能需要一些修补! (它确实需要GD库)

I had written a peice of code like this for another project I've done. I've copied it below, might need a bit of tinkering! (It does required the GD library)

这些是它需要的参数:

$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

它将向下或向上缩小图像到最大宽度或高度

It will scale down or up an image to the maximum width or height

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,0,0,0,0,$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,$new_thumb_loc,80);
    }

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

    return $result;
}

这篇关于使用PHP缩放图像并保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆