Skip to content

Instantly share code, notes, and snippets.

Last active Oct 23, 2015
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|
sources.each do |item|
full_path = item.match(%r{4x/(.*/)(.*\.*)})
subdir_path = full_path.captures[0]
file_name = full_path.captures[1]
image =
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:
image.resize "#{target_dir[:size_factor] * 100}%"
# Write resized image into the new directory
image.write "#{directory}/#{file_name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment