开发者

Programatically select the largest image from an array of image URLS in PHP?

I've got an array with 4-5 local image urls in it.

I want to开发者_运维问答 programatically return the URL of the largest image by image dimension in the array. How do I do that?


A very simplistic approach would be:

$files = array_combine($filenames,
  array_map("array_sum", array_map("getimagesize", $filenames))
);
arsort($files);

print key($files);    # largest image

This just adds $width+$height and checks for which file this adds up to the largest amount. Similar results to multiplying the two values. But in practice you might want to manually search for the max() value of width and height, if a 15x1000 should be treated as larger than 550x550.


getimagesize is what you want here. I've coded this in a very learn-friendly way. There are more advanced ways to do this, but they sometimes get obtuse.

$largest = -1;
$largest_image = null;

foreach ($images as $image)
{
    $size = getimagesize($image);
    $val = $size[0] * $size[1];
    if ($val > $largest)
    {
        $largest_image = $image;
        $largest = $val;
    }
}
if ($largest_image != null) 
{
   // do magic
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜