使用WideImage PHP库调整图像大小时保持纵横比 [英] Keeping aspect ration when resizing images using WideImage PHP library

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

问题描述

我希望将图片调整为预定义的最大尺寸,并在WideImage Library的帮助下保持宽高比。

I am looking to resize an image to a pre-defined maximum size keeping the aspect ratio with the help of WideImage Library.

示例:

允许的最大尺寸:200x200

Maximum Allowed Dimesions: 200x200

输入图像尺寸:300x200徽标(1,5:1宽高比比率),

Input Image Dimension: 300x200 logo (1,5:1 aspect ratio),

当前输出图像尺寸:200x200

Current Output Image Dimension: 200x200

预期输出图像尺寸:200x133(1,5: 1长宽比)。

Expected Output Image Dimension : 200x133 (1,5:1 aspect ratio).

目前,当宽高比改变时,图像会失真。应该怎么做才能保持宽高比?

Currently the images are distorted as aspect ratio is changed. What should be done to keep that aspect ratio?

我使用的是下面的代码。

I am using the code found below.

$targetWidth = 200;
$targetHeight = 200;

$sourceRatio = $sourceWidth / $sourceHeight;
$targetRatio = $targetWidth / $targetHeight;

if ( $sourceRatio < $targetRatio ) {
    $scale = $sourceWidth / $targetWidth;
} else {
    $scale = $sourceHeight / $targetHeight;
}

$resizeWidth = (int)($sourceWidth / $scale);
$resizeHeight = (int)($sourceHeight / $scale);


$img->resize($resizeWidth, $resizeHeight)

PS:我从调整图像大小而不失真保持纵横比,然后使用WideImage裁剪多余的内容

推荐答案

这个简单的逻辑来到我的帮助。

This simple logic came to my help.

$targetWidth = 200;
$targetHeight = 200;

$ratio = $srcWidth / $srcHeight;

if ($ratio > 1) {
    $resizeWidth = $targetWidth;
    $resizeHeight= $targetHeight / $ratio;
} else {
    $resizeWidth = $targetWidth * $ratio;
    $resizeHeight= $targetHeight;
}

$img->resize($resizeWidth, $resizeHeight)

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

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