开发者

Random Image Auto Rescale

I am currently using http://photomatt.net/scripts/randomimage to display a random background image. I would like to have these images automatically rescale (dynamically?) according to the window or div width. Is this even possible? Code would be incredible if you have the time and ability. :)

Th开发者_如何转开发anks in advance!

Here is the current random image code for your convenience:

<?php
// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
        if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
            $files[] = $file; // it's good
            ++$i;
        }
    }
}
closedir($handle); // We're not using it anymore
mt_srand((double) microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]); // Voila!


Well, I would probably take the javascript approach.

  1. Load the image up behind the scenes in a hidden image element.
  2. Bind to the image element's onload event so you know when it's completed.
  3. Get the width/height of the image after it's loaded and use that to apply CSS/etc. to the page based on what the browser looks like, the image size is, etc.

Pseudo-Code:

var body = document.getElementsByTagName('body')[0];
var img = document.createElement('img');

img.src = 'random_image.php';
img.style.display = 'none';
img.onload = function(){
  // modify the background styles based on your own conditions
};
body.appendChild(img);

If you really wanted to get fancy, you could bind to the window re-size event and continue to change the random image based on what the visible screen size, browser window size, etc. are.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜