Results 1 to 3 of 3

Thread: php random image

  1. #1
    Join Date
    Mar 2009
    Posts
    42
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default php random image

    Hi all,

    This one has got me thinking?

    Is there a way to make this array random for images with .jpg extension, instead of file names as list here?

    PHP Code:

    <?php // random image by file
    $images = array(
      array(
    'file'    => '2000-09painting4',
            
    'caption' => ''),
      array(
    'file'    => '2000-09painting7',
            
    'caption' => ''),


      );
    $i rand(0count($images)-1);
    $selectedImage "img/random/paintings/{$images[$i]['file']}.jpg";
    $caption $images[$i]['caption'];
    if (
    file_exists($selectedImage) && is_readable($selectedImage)) {
      
    $imageSize getimagesize($selectedImage);
      }
    ?>
    Thank you for your help and suggestions.

    John.
    Last edited by john0611; 08-11-2009 at 04:28 PM.

  2. #2
    Join Date
    Mar 2007
    Location
    New York, NY
    Posts
    557
    Thanks
    8
    Thanked 66 Times in 66 Posts

    Default

    You can retrieve an array of all images listed under one directory, and have them randomized.

    PHP Code:
    <?php

     $imgdir 
    '/myDir/'// the directory, where your images are stored
     
    $allowed_types = array('jpg','jpeg'); // list of filetypes you want to show
     
    $dimg opendir($imgdir);
     while(
    $imgfile readdir($dimg)) {
     if(
    in_array(strtolower(substr($imgfile,-3)),$allowed_types)) {
     
    $a_img[] = $imgfile;
          
    sort($a_img);
     
    reset ($a_img);
     } 
    }

    $images = Array();

    $totimg count($a_img); // total image number
    for($x=0$x $totimg$x++) {
    $size getimagesize($imgdir.'/'.$a_img[$x]);

    $halfwidth ceil($size[0]/2);
    $halfheight ceil($size[1]/2);

    echo 
    'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />';

    $images += array('file'    => $a_img[$x],
                     
    'caption' => '');

    }


    $i rand(0count($images)-1);
    $selectedImage "img/random/paintings/{$images[$i]['file']}.jpg";
    $caption $images[$i]['caption'];
    if (
    file_exists($selectedImage) && is_readable($selectedImage)) {
      
    $imageSize getimagesize($selectedImage);
      }
    ?>
    HTH
    - Josh

  3. The Following User Says Thank You to JShor For This Useful Post:

    john0611 (08-11-2009)

  4. #3
    Join Date
    Mar 2009
    Posts
    42
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Default

    Thanks for that JShor.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •