Skip to content

Instantly share code, notes, and snippets.

@6david9
Last active November 13, 2024 09:31
Show Gist options
  • Save 6david9/1449778642797e14dd6435da53004837 to your computer and use it in GitHub Desktop.
Save 6david9/1449778642797e14dd6435da53004837 to your computer and use it in GitHub Desktop.
Down scale png image from @3x to @2x, @1x
#! /usr/bin/env ruby
require 'mini_magick'
# gem install mini_magick
def resize_image(image_name, output_name)
current_scale = 3
if image_name.include?("@3x")
current_scale = 3
elsif image_name.include?("@2x")
current_scale = 2
end
image = MiniMagick::Image.open(image_name)
target_scale = current_scale - 1
while target_scale > 0 do
target_width = image.width * target_scale / current_scale
target_height = image.height * target_scale / current_scale
# puts "width: #{image.width}, height: #{image.height}"
# puts "target width: #{target_width}, target height: #{target_height}"
image.resize "#{target_width}x#{target_height}"
image.format "png"
if !Dir.exist?('output')
Dir.mkdir('output')
end
name = File.basename(image_name, ".*")
name = name.split("@").first
scale_name = "@#{target_scale.to_i}x"
image.write "output/#{output_name || name}#{scale_name}.png"
current_scale_name = "@#{current_scale.to_i}x"
unless image_name.include?(current_scale_name)
system "cp #{image_name} output/#{output_name || name}#{current_scale_name}.png"
else
system "cp #{image_name} output/#{image_name}"
end
target_scale -= 1
end
end
def usage
puts "Usage: change-size <image_name> [output_name]"
puts "Usage: change-size <folder_name>"
exit 1
end
image_or_folder_name = ARGV[0]
output_name = ARGV[1] # optional
if image_or_folder_name.nil? || (File.directory?(image_or_folder_name) && !Dir.exist?(image_or_folder_name)) || !File.exist?(image_or_folder_name)
usage
end
if !File.directory?(image_or_folder_name) && output_name && output_name.end_with?(".png")
output_name = output_name.gsub(/\.png$/, "")
end
if File.directory?(image_or_folder_name)
Dir.glob(File.join(image_or_folder_name, "**", "*.png")).each do |file|
resize_image(file, output_name)
end
else
resize_image(image_or_folder_name, output_name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment