Skip to content

Instantly share code, notes, and snippets.

@obahareth
Last active Oct 23, 2015
Embed
What would you like to do?
Resize Images Using MiniMagick While Preserving Subdirectory Structure
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