时当使用轨道资产管道,例如image_tag "logo.png"
导致以下HTML:包括图像的宽度和高度使用导轨资产管道
<img src="/assets/logo-0c1cd0fb.png">
是否有可能为导轨检测图像尺寸(宽度和高度)自动,使得它产生一个HTML包括尺寸为更快的页面渲染,像这样:
<img src="/assets/logo-0c1cd0fb.png" width="230" height="32">
时当使用轨道资产管道,例如image_tag "logo.png"
导致以下HTML:包括图像的宽度和高度使用导轨资产管道
<img src="/assets/logo-0c1cd0fb.png">
是否有可能为导轨检测图像尺寸(宽度和高度)自动,使得它产生一个HTML包括尺寸为更快的页面渲染,像这样:
<img src="/assets/logo-0c1cd0fb.png" width="230" height="32">
既然你可能需要一半大小的视网膜图像,我想改善@ 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 [email protected]@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
image_tag("logo.png", :size => "230x32")
应该这样做
使用https://github.com/sdsykes/fastimage,然后将它传递给IMAGE_TAG
感谢Thomas我(在你的Gemfile
需要gem "fastimage"
)
def image_tag(source, options = {})
if !options[:size] # Do not overwrite size if already set by caller
@@image_size ||= {} # Cache for image sizes
if [email protected]@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
要自动包含图像尺寸,您可以使用dimensions-rails。
您还可以使用dimensions gem(需要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
谢谢,但我不想在每次更改图像时使用图像的每个页面上手动更改此设置。 Rails应该自动检测图像大小。 – iblue