I am using Ruby on Rails v3.0.9 and I would like to check if an image (in my case a favicon.ico
icon image) is successfully retrieved from a web site and if not I would like to display a custom image.
In order to retrieve the favicon.ico
image related to a web site, in my view file I have:
image_tag "#{web_site.link}/favicon.ico", :size => "16x16"
where web_site.link
values are something like the followings:
http://stackoverflow.com/
http://www.stackoverflow.com/
http://facebook.com/
...
How to check if an image was found on a web site (maybe using an if ... else ... end
statement or performing some HTTP request before to handle favicon images) and how to handle the above scenario?
You can use the reverse Google image feature offered by Google who has the most extensive database on the internet.
Go to Tineye.com, then either upload the address of the image or upload the image itself, and the site will crawl the net looking for the image or a very close replica of it. It will list the site where it has been posted, and the dates it was posted.
Google's reverse image search is a good way to get a rough overview of whether an image has been used on other websites – and, if so, how often. This search shows you similar images, other sizes of the image you're looking for, and any websites, blogs, and profiles that are using the stolen image.
Here's how to implement the idea you had in the original question.
The issue with this approach will be that your response times will include however long it takes for the other domain to respond to your request for the image. If that site is having issues, then your page wont load until the request times out.
<%
img_url = 'http://adomain.com/image.jpg'
res = Net::HTTP.get_response(URI.parse(img_url))
img_url = '[my alternate url]' unless res.code.to_i >= 200 && res.code.to_i < 400 #good codes will be betweem 200 - 399
%>
<%=image_tag img_url%>
The jQuery approach is a bit more involved. I'd suggest something along the following:
<img>
tag with a transparent spacer image$.ajax
call for the remote image
<img>
's src with the remote images's url<img>
's src with the fallback image's urlUnfortunately, I don't have time to generate the exact code for this right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With