检查图像是否为空PHP

时间:2013-12-21 11:00:29

标签: php image is-empty

我正在尝试创建一个PHP脚本来获取用户图片但是当我返回的图像为空时,它应该返回标准图像。这是我的代码不起作用......

<?php
if (isset($_GET['user']))
{
$user = $_GET['user'];
$skinURL = "http://s3.amazonaws.com/MinecraftSkins/".$user.".png";
} 
$debugImage = imagecreatefrompng("http://s3.amazonaws.com/MinecraftSkins/".$user.".png");
if (empty($debugImage)) // here it checks if $debugImage is empty (doesn't work)
{
    $skinURL = 'http://www.minecraft.net/images/char.png';
}
$skin = imagecreatefrompng($skinURL);
?>

任何想法?

编辑1:如果图像存在,则链接返回图像,如果图像不存在则返回任何内容。谢谢你的回答!

2 个答案:

答案 0 :(得分:6)

没有&#34;空图像&#34;。即使它是空白图像,仍然存在具有相同颜色的像素,这很难归类为&#34;空&#34;。相反,为什么不检查文件是否存在?

function c_file_exists($file){
    $file_headers = @get_headers($file);
    if(strpos($file_headers[0], '404 Not Found')) {
        return false;
    }
    return true;
}
if (!c_file_exists("http://s3.amazonaws.com/MinecraftSkins/".$user.".png"))
{
    $skinURL = 'http://www.minecraft.net/images/char.png';
}

来源:http://www.php.net/manual/en/function.file-exists.php#75064

修改

我编辑了函数的条件以使用不同版本的HTTP,因为2现在已经出局,有人可能仍在使用1.0

答案 1 :(得分:0)

这里有两点需要注意:

首先,在您的环境设置中ensure allow_url_fopen is enabled

其次,添加一项检查以确保远程文件存在。您可以发出卷曲请求来执行此操作。或者在他的回答中使用php_nub_qq提到的方法。

更好的是,在调用imagecreatefrompng之前,将远程映像复制到服务器。看看this thread

相关问题