检查网址中的图片大小

时间:2012-05-07 20:11:24

标签: php image url image-size

我找到了一个漂亮的小PHP函数来检查一个url是否是一个图像 - 是否还有一种方法来确定该图像是否是例如> 1MB?

解决方案:

我在这里找到了一个可行的解决方案:php how to get web image size in kb?

2 个答案:

答案 0 :(得分:2)

来自:https://stackoverflow.com/a/3894706/187954

<?php
$headers = get_headers('http://humus101.com/wp-content/uploads/2009/11/Hummus-soup.jpg');
$size = null;
foreach($headers as $h){
    /** look for Content-Length, and stick it in $size **/
}
if ($size === null){ //we didn't get a Content-Length header
    /** Grab file to local disk and use filesize() to set $size **/
}

echo "image is $size bytes";

答案 1 :(得分:1)

我会参考这篇文章,我认为它会回答你的问题。 Easiest way to grab filesize of remote file in PHP?

有两种方法(我知道)。一种是使用CURL并仅获取标题(更高效,更不可靠)和file_get_contents (more reliable, less efficient)

使用CURL,您只能得到CONTENT_LENGTH标题,即文件大小。然后你可以从那里做简单的数学运算,看它是否超过1mb。问题是远程服务器可能不支持该功能。

通过使用strlen(file_get_contents("YOUR URL")),您可以获取文件中的总字节数,但脚本必须先下载文件,如果是大图像则会出现问题。

要检查文件类型,可以使用substr检查文件扩展名。

这样的事情可行,但有其自身的问题

$ext = substr($URL, -3, 3);

if($ext == 'jpg' || $ext == 'gif') {
   //is image
}else{
   //not image
}