Skip to content

Instantly share code, notes, and snippets.

@obahareth
Last active October 23, 2015 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obahareth/5140833efcc7a326bf27 to your computer and use it in GitHub Desktop.
Save obahareth/5140833efcc7a326bf27 to your computer and use it in GitHub Desktop.
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