Search code examples
htmlruby-on-railsrubymime

Rails -nokogiri GEM: Detect MIME type of image in URL


I am using gem nokogiri to scrap img tag src values. Sometimes url doesn't show the image file name with extension.

So I am trying to detect the image MIME type as follows:

MIME::Types.type_for("http://web.com/img/12457634").first.content_type # => "image/gif"

But it shows error:

undefined method `content_type' for nil:NilClass (NoMethodError)

Any solution?


Solution

  • You get this error:

    undefined method `content_type' for nil:NilClass (NoMethodError)
    

    because the MIME::Types.type_for("http://web.com/img/12457634").first object is nil sometimes.

    To avoid this problem, do this:

    MIME::Types.type_for("http://web.com/img/12457634").first.try(:content_type)
    

    So, it does not crash your program if it's nil. If it's not nil, you get the correct content_type

    Alternatively, to check the Content-Type header for image using Net::HTTP, you can write a method like this:

    def valid_image_exists?(url)
        url = URI.parse(url)
        Net::HTTP.start(url.host, url.port) do |http|
          return http.head(url.request_uri)['Content-Type'].start_with? 'image'
        end
    end