middleman/middleman-core/lib/middleman-core/extensions/automatic_image_sizes.rb

49 lines
1.5 KiB
Ruby
Raw Normal View History

# Automatic Image Sizes extension
class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
def initialize(app, options_hash={}, &block)
super
# Include 3rd-party fastimage library
2014-05-27 03:00:39 +02:00
require 'fastimage'
end
helpers do
# Override default image_tag helper to automatically calculate and include
# image dimensions.
#
# @param [String] path
# @param [Hash] params
# @return [String]
def image_tag(path, params={})
2014-04-29 19:50:21 +02:00
if !params.key?(:width) && !params.key?(:height) && !path.include?('://')
2014-07-16 03:01:45 +02:00
real_path = path.dup
2014-01-01 03:21:30 +01:00
real_path = File.join(config[:images_dir], real_path) unless real_path.start_with?('/')
2016-01-23 00:57:07 +01:00
file = app.files.find(:source, real_path) || app.files.find(:source, real_path.sub(/^\//, ''))
2014-07-16 03:01:45 +02:00
if file && file[:full_path].exist?
begin
2015-09-19 23:07:42 +02:00
full_path = file[:full_path].to_s
width, height = ::FastImage.size(full_path, raise_on_failure: true)
# Check for @2x and @3x image
2015-05-09 11:15:16 +02:00
retina = full_path.match(/@(\d)x\.[a-zA-Z]{3,4}$/)
if retina
2015-09-17 22:53:43 +02:00
factor = retina[1].to_i
2015-05-16 22:21:12 +02:00
width /= factor
height /= factor
end
params[:width] = width
params[:height] = height
rescue FastImage::UnknownImageType
# No message, it's just not supported
rescue
2014-04-29 19:50:21 +02:00
warn "Couldn't determine dimensions for image #{path}: #{$ERROR_INFO.message}"
end
end
end
super(path, params)
end
end
end