How to check if an image exists on the web

Posted by Paolo Sat, 09 Jun 2007 10:32:00 GMT

require 'net/http'
require 'uri'

def exist?(image_url)
  Timeout::timeout(5) do
    url = URI.parse(image_url)
    req = Net::HTTP::Head.new(url.path)
    res = Net::HTTP.start(url.host, url.port) do |h| 
      h.request(req)
    end
    return res.message.strip.downcase == "ok"
  end
rescue Exception
  false
end

# usage:
exist? 'http://www.seesaw.it/images/logo.png' #=> true
exist? 'http://foo.com/bar.gif' #=> false

Socialize it: Add to del.icio.us Digg it! Technorati: How to check if an image exists on the web Add to reddit.com

Posted in  | Tags , , , ,  | no comments | no trackbacks


SeeSaw srl - Via Monte Pasubio, 8 37126 Verona - tel +39 045 4857457 fax 045 4851151 P.Iva 03609790237