如何让“找不到图片”如果函数中使用的图像返回错误


How to have a "no image found" icon if the image used in the function returns an error?

在我的应用程序中,我使用timthumb来调整图像的大小。这些图片不是由我控制的,因为我从RSS订阅中获得它们。有时图像不显示在我的页面。当我用timthumb检查整个链接时,我得到了这个

警告:imagecreatefromjpeg (http://www.domain.com/image.jpg)(函数。imagecreatefromjpeg]:打开HTTP请求失败失败了!HTTP/1.1在/timthumb.php第193行中找不到404打开图片:http://www.domain.com/image.jpg

所以,我正在寻找一种方法来知道什么时候图像返回一个错误,这样我就不会在页面上显示它(红色X图标)。

从我的RSS提要中,我使用正则表达式获得第一个图像

if (thumb[0]) { show the image using timthumb } 
else { show a no-image icon } 

但是上面的例子属于"show the image using timthumb"

这是从我的代码粘贴http://codepad.org/7aFXE8ZY

谢谢。

您可以使用curl获取给定url的标头,并检查HTTP状态码和image/*内容类型。

如果你的url指向一个图像,下面的函数将返回true,否则返回false

注意curl_setopt($ch, CURLOPT_NOBODY, 1);行,它告诉curl只获取给定页面的标题,而不是整个内容。这样在检查图像是否存在时可以节省带宽。

<?php
function image_exist($url, $check_mime_type = true) {    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    if (!preg_match('/^HTTP'/1.1 200 OK/i', $result)) {
        // status != 200, handle redirects, not found, forbidden and so on
        return false;
    }
    if ($check_mime_type && !preg_match('/^Content-Type:''s+image'/.*$/im', $result)) {
        // mime != image/*
        return false;
    }
    return true;
}
$url = 'http://static.php.net/www.php.net/images/php.gif';
var_dump(image_exist($url)); // return true since it's an image
$bogus_url = 'http://www.google.com/foobar';
var_dump(image_exist($bogus_url)); // return false since page doesn't exist
$text_url = 'http://stackoverflow.com/';
var_dump(image_exist($text_url)); // return false since page exists but it's a text page

通过使用此代码,您可以避免@错误抑制操作符,该操作符不应该使用,并且仅在存在时获取实际图像。

@是坏的,因为它会抑制甚至致命的错误,所以你的脚本可能会死于一个空白页面,你不知道为什么,因为它会将error_reporting设置为0,并将其恢复到之前的值,见这里的警告。

此外,它还会降低您的代码速度,如本注释和以下注释所述。

如果imagecreatefromjpeg跳过一个错误(比如文件不可读),它将返回false,并且根据服务器配置输出一条错误消息。输出错误消息(或任何)使php自动发送请求头。在发送了标头之后,你不能将它们收回来表明你实际上是在发送图像而不是HTML文档。

因此,您可能希望抑制错误输出,如下所示:
set_error_handler(function($en, $es) {}, E_WARNING);
$im = imagecreatefromjpeg($url);
restore_error_handler();
if ($im === false) {
   header('Content-Type: image/jpeg');
   readfile('static/red-x-icon.jpeg');
   exit();
}
// Continue processing $im, eventually send headers and the image itself

使用set_error_handler()创建一个错误处理程序,如果抛出错误,只返回一个空白图像,并可能在其他地方记录错误。

为什么不先打开图像文件呢?

function fileExists($path){
    return (@fopen($path,"r")==true);
}
$img = 'no_image.jpg';
if (fileExists(thumb[0])) {
    $img = thumb[0];
}

另外,您是否检查以确保您没有将非jpeg(PNG等)图像传递给imagecreatefromjpeg()?

当未设置用户代理时,页面不允许下载图像时,可能会出现这个问题。在运行imagecreatefromjpeg之前尝试设置一个。例如:

ini_set('user_agent', 'Mozilla/5.0 (Windows NT 5.1; U; rv:5.0) Gecko/20100101 Firefox/5.0');