我正在创建一个“图像生成器”,用户可以在其中上传图像并添加文本和/或在图像上绘图。输出的图像是固定大小 (698x450)。
在客户端,当用户上传他们的图片时,它被设置为 698x450 的 div 背景,背景大小为:封面。这使它很好地填充了该区域。
最终的组合图像由 PHP 使用 GD 函数生成。我的问题是,如何让图像在 PHP 中像在 CSS 中一样进行缩放。我希望 PHP 脚本的结果看起来与图像在 CSS 中设置的一样,就像上面那样。 有谁知道使用 background-size:cover 的浏览器如何计算如何适本地缩放图像?我想将其翻译成 PHP。
谢谢
最佳答案
这是封面计算背后的逻辑。
你有四个基本值:
imgWidth // your original img width
imgHeight
containerWidth // your container width (here 698px)
containerHeight
从这些值得出的两个比率:
imgRatio = (imgHeight / imgWidth) // original img ratio
containerRatio = (containerHeight / containerWidth) // container ratio
您想找到两个新值:
finalWidth // the scaled img width
finalHeight
所以:
if (containerRatio > imgRatio)
{
finalHeight = containerHeight
finalWidth = (containerHeight / imgRatio)
}
else
{
finalWidth = containerWidth
finalHeight = (containerWidth / imgRatio)
}
...你有一个相当于背景大小的封面。
关于css - CSS 背景大小 :cover 背后的数学原理是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10285134/