2013-04-20 23:27:25 +02:00
|
|
|
# Automatic Image Sizes extension
|
|
|
|
class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
|
|
|
|
def initialize(app, options_hash={}, &block)
|
|
|
|
super
|
2013-04-20 22:32:39 +02:00
|
|
|
|
2013-04-20 23:27:25 +02:00
|
|
|
# Include 3rd-party fastimage library
|
2013-12-28 01:26:31 +01:00
|
|
|
require 'vendored-middleman-deps/fastimage'
|
2013-04-20 23:27:25 +02:00
|
|
|
end
|
2013-04-20 22:32:39 +02:00
|
|
|
|
2013-04-20 23:27:25 +02:00
|
|
|
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 01:02:18 +02:00
|
|
|
if !params.key?(:width) && !params.key?(:height) && !path.include?('://')
|
2013-04-20 23:27:25 +02:00
|
|
|
real_path = path
|
|
|
|
real_path = File.join(images_dir, real_path) unless real_path.start_with?('/')
|
|
|
|
full_path = File.join(source_dir, real_path)
|
2013-04-20 22:32:39 +02:00
|
|
|
|
2014-04-29 01:02:18 +02:00
|
|
|
if File.exist?(full_path)
|
2013-04-20 23:27:25 +02:00
|
|
|
begin
|
2014-04-29 19:44:24 +02:00
|
|
|
width, height = ::FastImage.size(full_path, raise_on_failure: true)
|
2015-05-08 23:18:11 +02:00
|
|
|
# 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}$/)
|
2015-05-08 23:18:11 +02:00
|
|
|
if retina
|
|
|
|
factor = retina[1].to_i
|
2015-05-16 22:21:12 +02:00
|
|
|
width /= factor
|
|
|
|
height /= factor
|
2015-05-08 23:18:11 +02:00
|
|
|
end
|
2013-04-20 23:27:25 +02:00
|
|
|
params[:width] = width
|
|
|
|
params[:height] = height
|
|
|
|
rescue FastImage::UnknownImageType
|
|
|
|
# No message, it's just not supported
|
|
|
|
rescue
|
2014-04-29 01:02:18 +02:00
|
|
|
warn "Couldn't determine dimensions for image #{path}: #{$ERROR_INFO.message}"
|
2013-04-20 22:32:39 +02:00
|
|
|
end
|
2012-05-25 01:14:17 +02:00
|
|
|
end
|
|
|
|
end
|
2013-04-20 23:27:25 +02:00
|
|
|
|
|
|
|
super(path, params)
|
2012-05-25 01:14:17 +02:00
|
|
|
end
|
|
|
|
end
|
2012-07-09 09:16:54 +02:00
|
|
|
end
|