2014-12-08 00:06:28 +11:00
|
|
|
module Jekyll
|
|
|
|
class ResponsiveImage
|
|
|
|
class ResizeHandler
|
2014-12-08 09:03:26 +11:00
|
|
|
include ResponsiveImage::Utils
|
|
|
|
|
2014-12-08 00:06:28 +11:00
|
|
|
def resize_image(img, config)
|
|
|
|
resized = []
|
|
|
|
|
|
|
|
config['sizes'].each do |size|
|
|
|
|
width = size['width']
|
|
|
|
ratio = width.to_f / img.columns.to_f
|
|
|
|
height = (img.rows.to_f * ratio).round
|
|
|
|
|
|
|
|
next unless needs_resizing?(img, width)
|
|
|
|
|
2016-09-02 17:53:29 +10:00
|
|
|
image_path = img.filename.force_encoding(Encoding::UTF_8)
|
|
|
|
filepath = format_output_path(config['output_path_format'], config['base_path'], image_path, width, height)
|
2015-12-28 09:41:04 +11:00
|
|
|
resized.push(image_hash(config['base_path'], filepath, width, height))
|
2014-12-08 00:06:28 +11:00
|
|
|
|
|
|
|
# Don't resize images more than once
|
2016-06-06 07:32:13 +10:00
|
|
|
next if File.exist?(filepath)
|
2014-12-08 00:06:28 +11:00
|
|
|
|
|
|
|
ensure_output_dir_exists!(File.dirname(filepath))
|
|
|
|
|
|
|
|
Jekyll.logger.info "Generating #{filepath}"
|
|
|
|
|
|
|
|
i = img.scale(ratio)
|
|
|
|
i.write(filepath) do |f|
|
|
|
|
f.quality = size['quality'] || config['default_quality']
|
|
|
|
end
|
|
|
|
|
2015-11-05 09:55:32 +11:00
|
|
|
# Ensure the generated file is copied to the _site directory
|
|
|
|
site_dest_filepath = File.expand_path(filepath, config[:site_dest])
|
|
|
|
ensure_output_dir_exists!(File.dirname(site_dest_filepath))
|
|
|
|
FileUtils.copy(filepath, site_dest_filepath)
|
|
|
|
|
2014-12-08 00:06:28 +11:00
|
|
|
i.destroy!
|
|
|
|
end
|
2016-06-06 07:32:13 +10:00
|
|
|
|
2016-03-17 04:35:34 +11:00
|
|
|
img.destroy!
|
2014-12-08 00:06:28 +11:00
|
|
|
|
|
|
|
resized
|
|
|
|
end
|
|
|
|
|
|
|
|
def needs_resizing?(img, width)
|
|
|
|
img.columns > width
|
|
|
|
end
|
|
|
|
|
|
|
|
def ensure_output_dir_exists!(dir)
|
2016-06-06 07:32:13 +10:00
|
|
|
unless Dir.exist?(dir)
|
2014-12-08 00:06:28 +11:00
|
|
|
Jekyll.logger.info "Creating output directory #{dir}"
|
|
|
|
FileUtils.mkdir_p(dir)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|