Last active
October 23, 2015 10:11
-
-
Save obahareth/5140833efcc7a326bf27 to your computer and use it in GitHub Desktop.
Resize Images Using MiniMagick While Preserving Subdirectory Structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'fileutils' | |
require 'mini_magick' | |
# Get all files of any type within the 4x folder, within any subdirectory | |
sources = Dir.glob(File.join('**', '4x', '**', '*.png')) | |
# Create our target directories, and the size factor for that directory | |
target_directories = [ | |
{ name: '2x', size_factor: 0.5 }, | |
{ name: '1x', size_factor: 0.25 } | |
] | |
# Delete old directories and make new ones | |
target_directories.each do |dir| | |
FileUtils.rm_rf(dir[:name]) | |
Dir.mkdir(dir[:name]) | |
end | |
sources.each do |item| | |
full_path = item.match(%r{4x/(.*/)(.*\.*)}) | |
subdir_path = full_path.captures[0] | |
file_name = full_path.captures[1] | |
image = MiniMagick::Image.open(full_path.to_s) | |
target_directories.each do |target_dir| | |
# Create subdirectories inside target directories with the same exact | |
# subdirectory structure as the source | |
directory = "#{target_dir[:name]}/#{subdir_path}" | |
FileUtils.mkdir_p directory | |
# Resize using Image Magick's percentage format, see: | |
# http://www.imagemagick.org/script/mogrify.php | |
image.resize "#{target_dir[:size_factor] * 100}%" | |
# Write resized image into the new directory | |
image.write "#{directory}/#{file_name}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment