views:

73

answers:

1
<?php
foreach (glob("*.jpg") as $filename) {
    echo "$filename size " . filesize($filename) . "<br>";
    echo '<img src="'.$filename.'" height=150px><br>';
}
?>

using that code, i am able to display all the images in the folder i want to display only one that meets a size parameter, and if there are more ignore them basically want to display the one thats like a box

and alternatively i want to display only the first image of that foreach loop and if there are no images display a default image

EDIT so

<?php
foreach (glob("*.jpg") as $filename) {
    $info = getimagesize($filename);
    if ($info[0] == $info[1]) {
        echo "$filename size " . filesize($filename) . "<br>";
        echo '<img src="'.$filename.'" height=150px><br>';
        break;
    }
}
?>

gives you an image if its a box, (thanks to schnaader) right but images that come close to a box should be included too, how can that be sorted, meaning if the height divided by width gives more than 1

+2  A: 

You can display only the first image by using break:

foreach (glob("*.jpg") as $filename) {
    echo "$filename size " . filesize($filename) . "<br>";
    echo '<img src="'.$filename.'" height=150px><br>';
    break;
}

For only printing the one that meets a specific size, use getimagesize and compare the width/height with the one you want, so basically use the code above, but wrap an if around the lines inside the foreach loop. The following could work, but I haven't used PHP for long, so don't rely on it:

foreach (glob("*.jpg") as $filename) {
    $info = getimagesize($filename);
    if ($info[0] == $width_i_want) {
      if ($info[1] == $height_i_want) {
        echo "$filename size " . filesize($filename) . "<br>";
        echo '<img src="'.$filename.'" height=150px><br>';
        break;
      }
    }
}

And if you want to get the square-sized image, use

if ($info[0] == $info[1]) {
  [...]

EDIT: To get the image which is closest to square-sized, try this:

$record_ratio = 0;
foreach (glob("*.jpg") as $filename) {
    $info = getimagesize($filename);
    $ratio = $info[0] / $info[1];
    if (abs(1 - $ratio) < abs(1 - $record_ratio)) {
      $record_ratio = $ratio;
      $record_filename = $filename;
    }
    if (record_ratio == 1) break;
}
if ($record_ratio > 0) {
  echo '<img src="'.$record_filename.'" height=150px><br>';
}

Variations of this can also give you the images sorted by ratio or images with a ratio between two values (for example 0.75 <= ratio <= 1.25).

schnaader
ohh right, how stupid of me,
vache
ok one sec let me try thanks
vache
great works, can i put a range to the square, such as ifthe image is close to a square but is not ==
vache
wow works perfect, thanks very much
vache