iblue
iblue

Reputation: 30404

Including image width and height when using the rails asset pipeline

When using the rails asset pipeline, for example image_tag "logo.png" leads to the following HTML:

<img src="/assets/logo-0c1cd0fb.png">

Is it possible for rails to detect the image dimensions (width and height) automatically, so that it generates an HTML including dimensions for faster page rendering, like this:

<img src="/assets/logo-0c1cd0fb.png" width="230" height="32">

Upvotes: 3

Views: 2749

Answers (5)

Ariel
Ariel

Reputation: 1661

To include the image dimensions automatically you can use dimensions-rails.

You can also use the dimensions gem (requires gem "dimensions") to render retina image tags.

def retina_image_tag(source, options = {})
  unless options[:size] or options[:width] or options[:height]
    fs_path = ::Rails.application.assets.find_asset(source)
    fs_path = fs_path.present? ? fs_path.pathname : File.join(::Rails.public_path, source)

    if fs_path.present? and File.exist? fs_path
      options[:width], options[:height] = ::Dimensions.dimensions(fs_path).map do |x| x/2 end
    end
  end

  image_tag(source, options)
end

Upvotes: 1

knagode
knagode

Reputation: 6125

Since you probably need half size for retina images I would like to improve @iblue's answer. I changed some lines to achieve this easier. You need fastimage gem & put the following code in ApplicationHelper.

  def retina_image_tag(source, options = {})
    if !options[:size] # Do not overwrite size if already set by caller
      @@image_size ||= {} # Cache for image sizes
      if !@@image_size[source] # Fill cache
        @@image_size[source] = FastImage.size(::Rails.root.to_s+"/app/assets/images/#{source}", :raise_on_failure => true)
        @@image_size[source] = [@@image_size[source][0]/2, @@image_size[source][1]/2]
      end
      options = options.merge(:style => "max-width:" + @@image_size[source][0].to_s + "px")
    end
    image_tag(source, options)
  end

Upvotes: 1

iblue
iblue

Reputation: 30404

Thanks to Thomas I came up with this (requires gem "fastimage" in your Gemfile)

def image_tag(source, options = {})
  if !options[:size] # Do not overwrite size if already set by caller
    @@image_size ||= {} # Cache for image sizes
    if !@@image_size[source] # Fill cache
      @@image_size[source] = FastImage.size(::Rails.root.to_s+"/app/assets/images/#{source}", :raise_on_failure => true).join("x")
    end
    options = options.merge(:size => @@image_size[source])
  end
  super(source, options)
end

Just add to your ApplicationHelper

Upvotes: 4

Thomas Rotter
Thomas Rotter

Reputation: 29

Use https://github.com/sdsykes/fastimage and then pass it to image_tag

Upvotes: 3

Thomas Rotter
Thomas Rotter

Reputation: 29

image_tag("logo.png", :size => "230x32") 

should do it

Upvotes: -2

Related Questions