Class: Jekyll::ResponsiveImage::ResizeHandler

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/jekyll/responsive_image/resize_handler.rb

Instance Method Summary collapse

Methods included from Utils

#format_output_path, #image_hash, #relative_dirname, #symbolize_keys

Instance Method Details

#ensure_output_dir_exists!(dir) ⇒ Object



48
49
50
51
52
53
# File 'lib/jekyll/responsive_image/resize_handler.rb', line 48

def ensure_output_dir_exists!(dir)
  unless Dir.exists?(dir)
    Jekyll.logger.info "Creating output directory #{dir}"
    FileUtils.mkdir_p(dir)
  end
end

#needs_resizing?(img, width) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/jekyll/responsive_image/resize_handler.rb', line 44

def needs_resizing?(img, width)
  img.columns > width
end

#resize_image(img, config) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/jekyll/responsive_image/resize_handler.rb', line 6

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)

    filepath = format_output_path(config['output_path_format'], config['base_path'], img.filename, width, height)
    resized.push(image_hash(config['base_path'], filepath, width, height))

    # Don't resize images more than once
    next if File.exists?(filepath)

    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

    # 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)

    i.destroy!
  end
  
  img.destroy!

  resized
end