Reputation:
I want to generate some random placekitten urls like so:
http://placekitten.com/200/300
To use as paceholders on the site I am developing at the moment. The images must be no smaller than 100px and no larger than 250px in width. I am generating the widths like so:
$width = mt_rand(100, 250);
But I am not sure how to generate the height. The height should be of the proper aspect ratio based on the random width that was generated. How to do that?
Ultimately the goal is:
$thumb = "http://placekitten.com/$width/$height";
Upvotes: 1
Views: 724
Reputation: 77778
Should be as simple as:
$ratio = 200/300;
$width = mt_rand(100, 250);
$height = round($width / $ratio);
See some examples:
$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";
}
Output
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
Upvotes: 1