2

使用 rails 资产管道时,例如image_tag "logo.png"会导致以下 HTML:

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

rails 是否可以自动检测图像尺寸(宽度和高度),以便生成包含尺寸的 HTML,以便更快地呈现页面,如下所示:

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

5 回答 5

4

感谢托马斯,我想出了这个(需要gem "fastimage"你的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

只需添加到您的ApplicationHelper

于 2013-08-29T15:21:09.927 回答
3

使用https://github.com/sdsykes/fastimage然后将其传递给 image_tag

于 2013-08-29T14:44:09.317 回答
1

由于您可能需要一半尺寸的视网膜图像,我想改进@iblue 的答案。我更改了一些行以更轻松地实现这一点。您需要fastimage gem并将以下代码放入 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
于 2015-01-22T11:58:34.013 回答
1

要自动包含图像尺寸,您可以使用dimensions-rails

您还可以使用尺寸 gem (requires gem "dimensions") 来渲染视网膜图像标签。

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
于 2015-08-17T20:42:09.780 回答
-2
image_tag("logo.png", :size => "230x32") 

应该这样做

于 2013-08-29T14:40:12.677 回答