我想生成一些随机的placekitten网址:
http://placekitten.com/200/300
在我正在开发的网站上用作竞速者。图像宽度不得小于100像素且不大于250像素。我正在生成这样的宽度:
$width = mt_rand(100, 250);
但我不知道如何产生高度。根据生成的随机宽度,高度应该是适当的宽高比。怎么做?
最终目标是:
$thumb = "http://placekitten.com/$width/$height";
答案 0 :(得分:1)
应该如此简单:
$ratio = 200/300;
$width = mt_rand(100, 250);
$height = round($width / $ratio);
参见一些例子:
$ratio = 200/300;
echo "base aspect ratio: ", round($ratio, 2), "\n\n";
foreach(range(1,10) as $_) {
$width = mt_rand(100, 250);
$height = round($width / $ratio);
echo "http://placekitten.com/{$width}/{$height}\n";
echo "aspect ratio: ", round($width / $height, 2), "\n\n";
}
输出
base aspect ratio: 0.67
http://placekitten.com/229/344
aspect ratio: 0.67
http://placekitten.com/112/168
aspect ratio: 0.67
http://placekitten.com/241/362
aspect ratio: 0.67
http://placekitten.com/223/335
aspect ratio: 0.67
http://placekitten.com/196/294
aspect ratio: 0.67
http://placekitten.com/234/351
aspect ratio: 0.67
http://placekitten.com/116/174
aspect ratio: 0.67
http://placekitten.com/157/236
aspect ratio: 0.67
http://placekitten.com/165/248
aspect ratio: 0.67
http://placekitten.com/114/171
aspect ratio: 0.67