已损坏的图像使用http响应标头替换

时间:2014-03-21 21:44:13

标签: image http http-headers

我想要隐藏损坏的图像图标,但我正在使用的图像服务器不会抛出404页面,而是将其重定向到其替代图像,因此我无法使用传统的onerror方法。 如果服务器在响应中抛出404页面,则此方法很有效。

<html>
<body> 
<div><img src="http://stackoverflow.com/image.jpg" alt="image" onerror="this.style.display='none'"/></div>
</body>
</html>

但条件是,图片网址为:http://tinypic.com/someimage.jpg 上述方法无效。因为这是一个302响应,它将其重定向到其他图像。我也想隐藏它。 是否有可能以某种方式使用http响应作为显示/隐藏图像的条件。

以下是上图中的http标题:

$ curl -I http://tinypic.com/notfound.jpg
HTTP/1.1 302 Found
Server: Apache
Location: http://tinypic.com/images/404.gif
Expires: Fri, 21 Mar 2014 21:33:07 GMT
Cache-Control: max-age=300
Content-Type: text/html; charset=iso-8859-1
Content-Length: 217
Accept-Ranges: bytes
Date: Fri, 21 Mar 2014 21:28:07 GMT
X-Varnish: 1535787681
Age: 0
Via: 1.1 varnish
Connection: keep-alive
X-Varnish-Server: den2tpv01
X-Cache: MISS

现在,我认为HTTP / 1.1 302 Found可以在某种程度上使用。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

在这里,简单的解决方案:

<img src="www.google.com/noanyimage.png" width="200px" height ="200px" onerror="this.src ='';" />

答案 1 :(得分:0)

这是使用php的解决方案......

<?PHP 
$url = "http://tinypic.com/notfound.jpg"; //Image link here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
$status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

if($status_code==302 or $status_code==301 or $status_code==404){
  echo "no image found"; 
}
else {
echo '<img src="'.$url.'" />';  
}
curl_close($ch);

?>