Class: PngOptimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/geordi/commands/png_optimize.rb

Instance Method Summary collapse

Instance Method Details

#batch_optimize_inplace(path) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/geordi/commands/png_optimize.rb', line 71

def batch_optimize_inplace(path)
  # Dir[".png"] works case sensitive, so to catch all funky .png extensions we have to go the following way:
  png_relative_paths = []
  Dir["#{path}/*.*"].each do |file_name|
    png_relative_paths << file_name if ends_with?(File.basename(file_name.downcase), '.png')
  end
  png_relative_paths.each do |png_relative_path|
    optimize_inplace(png_relative_path)
  end
end

#ends_with?(string, suffix) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/geordi/commands/png_optimize.rb', line 33

def ends_with?(string, suffix)
  string[-suffix.length, suffix.length] == suffix
end

#optimization_default_argsObject



37
38
39
40
41
42
43
# File 'lib/geordi/commands/png_optimize.rb', line 37

def optimization_default_args
  args = ''
  args << '-rem alla ' # remove everything except transparency
  args << '-rem text ' # remove text chunks
  args << '-reduce ' # eliminate unused colors and reduce bit-depth (if possible)
  args
end

#optimize_file(input_file, output_file) ⇒ Object



45
46
47
# File 'lib/geordi/commands/png_optimize.rb', line 45

def optimize_file(input_file, output_file)
  system "pngcrush #{optimization_default_args} '#{input_file}' '#{output_file}'"
end

#optimize_inplace(input_file) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/geordi/commands/png_optimize.rb', line 60

def optimize_inplace(input_file)
  temp_file = unused_tempfile_path(input_file)
  result = optimize_file(input_file, temp_file)
  if result
    FileUtils.rm(input_file)
    FileUtils.mv(temp_file.to_s, input_file.to_s)
  else
    Interaction.fail 'Error:' + $?
  end
end

#unused_tempfile_path(original) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/geordi/commands/png_optimize.rb', line 49

def unused_tempfile_path(original)
  dirname = File.dirname(original)
  basename = File.basename(original)
  count = 0

  loop do
    tmp_name = "#{dirname}/#{basename}_temp_#{count += 1}.png"
    break tmp_name unless File.exist?(tmp_name)
  end
end