Created
August 31, 2013 04:17
-
-
Save kfriend/6396198 to your computer and use it in GitHub Desktop.
Ruby: Split an image in two
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
#!/usr/bin/env ruby | |
# Takes a list of images as arguments and slices them in half | |
# All images should be in the same directory | |
require 'rubygems' | |
require 'RMagick' | |
include Magick | |
# Check to make sure at least one file was given | |
raise ArgumentError, "No files given. You must supply at least one file to split" if ARGV.empty? | |
# Some settings | |
#split_dir = 'split' # where the split files are stored, relative to where the files are located | |
crop_width = 0.5 # the percent to crop | |
i = 1 # Used to detect if currently working on the first or last image | |
j = 1 # Used to rename images sequentially | |
# Sort the files list in a more natural way | |
ARGV.sort_by! { |f| f.split("-")[1].to_i } | |
# Process the files | |
ARGV.each do |file| | |
if File.file?(file) # Make sure the argument is a file | |
# Gather information about the file | |
path = file.split('/') | |
file_name = path.pop | |
path = path.join('/') | |
name_parts = file_name.split('.') | |
ext = name_parts.pop | |
base = name_parts.join('.') | |
split_dir = "#{path}/#{base.split('-').shift}" | |
Dir.mkdir(split_dir) unless Dir.exists?(split_dir) | |
if i == 1 || i == ARGV.size | |
puts "#{file} was moved to #{split_dir}/#{j}.jpg" | |
`mv '#{file}' '#{split_dir}/#{j}.jpg'` | |
j += 1 | |
else | |
left_file = "#{split_dir}/#{j}.jpg" | |
j += 1 | |
right_file = "#{split_dir}/#{j}.jpg" | |
j += 1 | |
image = ImageList.new(file); | |
# Crop and save the left image | |
if image.crop(0, 0, image.columns * crop_width, image.rows).write(left_file) | |
puts "#{left_file} written successfully." | |
else | |
puts "FAILED: #{left_file}" | |
end | |
# Crop and save the right image | |
if image.crop(image.columns * crop_width, 0, image.columns, image.rows).write(right_file) | |
puts "#{right_file} written successfully." | |
else | |
puts "FAILED: #{right_file}" | |
end | |
end | |
i += 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment