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



80
81
82
83
84
85
86
87
88
89
# File 'lib/geordi/commands/png_optimize.rb', line 80

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)


43
44
45
# File 'lib/geordi/commands/png_optimize.rb', line 43

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

#optimization_default_argsObject



47
48
49
50
51
52
53
# File 'lib/geordi/commands/png_optimize.rb', line 47

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



55
56
57
# File 'lib/geordi/commands/png_optimize.rb', line 55

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

#optimize_inplace(input_file) ⇒ Object



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

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}", "#{input_file}")
  else
    fail 'Error:' + $?
  end
end

#unused_tempfile_path(original) ⇒ Object



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

def unused_tempfile_path(original)
  dirname = File.dirname(original)
  basename = File.basename(original)
  count = 0
  begin
    tmp_name = "#{dirname}/#{basename}_temp_#{count += 1}.png"
  end while File.exists?(tmp_name)
  tmp_name
end