Class: PhotoHelper::Compress

Inherits:
Thor
  • Object
show all
Includes:
Thor::Actions
Defined in:
lib/photo-helper/compress.rb

Instance Method Summary collapse

Instance Method Details

#images(folder = nil) ⇒ Object



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
43
44
45
46
47
48
49
# File 'lib/photo-helper/compress.rb', line 11

def images(folder = nil)
  folder ||= options[:folder]

  search_path = File.expand_path(folder)

  files =
    if options[:recursive]
      Dir["#{search_path}/**/*"]
    else
      Dir["#{search_path}/*"]
    end

  files.each do |file|
    next if File.basename(file, '.*').end_with? '.min'
    next unless FileHelper.is_jpeg?(file)

    image = MiniMagick::Image.open(file)
    orig_size = image.size

    image.combine_options do |b|
      b.sampling_factor '4:2:0'
      b.strip
      b.interlace 'JPEG'
      b.colorspace 'RGB'
      b.quality 85
    end
    next if orig_size == image.size
    puts "#{file} (#{(orig_size / image.size) * 100}%)"

    output_path =
      if options[:overwrite]
        file
      else
        File.join(File.dirname(file), File.basename(file, '.*') + '.min' + File.extname(file))
      end

    image.write output_path
  end
end