1

我想生成一些随机的 placekitten url,如下所示:

http://placekitten.com/200/300

在我目前正在开发的网站上用作领跑者。图片宽度不得小于 100 像素且不得大于 250 像素。我正在生成这样的宽度:

$width = mt_rand(100, 250);

但我不确定如何生成高度。根据生成的随机宽度,高度应具有适当的纵横比。怎么做?

最终目标是:

$thumb = "http://placekitten.com/$width/$height";
4

1 回答 1

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
于 2013-02-21T00:59:45.340 回答