计算保持父div的纵横比的图像大小的逻辑

时间:2013-04-17 16:56:40

标签: php logic

让我用一个例子来解释。

Lets say I have an Image of size

960px X 668px

I have a div which holds this image. The div size is
154px X 75px

此div可以有任何可变大小。

If we see that the aspect ratio of image and the aspect ratio of the div 
that holds image are different.

我需要做的就是使用PHP调整大小和裁剪图像,使其占用原始大小的最大可能高度和宽度,并保持保存此图像的div的宽高比。 我只需要一个逻辑来计算一个百分比,通过多少DIV宽度和高度相乘,使得结果尺寸更接近图像尺寸但不超过图像尺寸,并且宽高比率将与DIV相同但不是图像。

由于 Sharmila

1 个答案:

答案 0 :(得分:1)

好的,那么你需要检查你是否会使用宽度比或高度比。

img.with / div.with = ratio_w
img.height / div.height = ratio_h

然后,较高的比率是您需要使用的比率,以确保您的图像适合div。

举个例子,我们有

ratio_w = 960 / 154 = 6.2
ratio_h = 668 / 75 = 8.9

ratio_h是更高的,因此ratio_h是您的比率

然后,为了适合你的div,这里是resize calcul

960 / 8.9 = 108
668 / 8.9 = 75

逻辑与其他值相同。


如果没有调整大小的问题,我建议检查这个CSS属性

background-size: contain;