Created
January 17, 2010 20:24
-
-
Save ecavazos/279565 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'image_science' | |
| class Thumb | |
| class << self | |
| # if a :thumb_dir is provided then the thumb | |
| # will be saved in the sub directory provided | |
| # with the same name as the original otherwise | |
| # it will be saved with "_th" after the name | |
| def resize(path, size, options = {}) | |
| options[:thumb_dir] ||= "" | |
| ImageScience.with_image path do |img| | |
| img.cropped_thumbnail(size) do |thumb| | |
| name = name_thumb(path, options[:thumb_dir]) | |
| File.delete(name) if File.exist?(name) | |
| thumb.save(name) | |
| end | |
| end | |
| end | |
| def resize_all(dir_path, size, options = {}) | |
| options[:thumb_dir] ||= "" | |
| Dir.foreach(dir_path) do |file| | |
| img_types = /\.(jpg|jpeg|png|gif)$/ | |
| next unless file.match(img_types) | |
| next if file.match(/_th#{img_types}/ ) | |
| dir_path += "/" unless dir_path[-1] == "/" | |
| resize((dir_path + file), size, options) | |
| end | |
| end | |
| private | |
| def name_thumb(path, thumb_dir) | |
| parts = path.split("/") | |
| if thumb_dir.empty? | |
| extension = /\.\w+$/ | |
| name = parts.pop.gsub(extension, "") + "_th" + path.match(extension)[0] | |
| else | |
| name = parts.pop | |
| dir = parts.join("/") + "/" + thumb_dir | |
| Dir.mkdir(dir) if !Dir.exist?(dir) | |
| name = thumb_dir + "/" + name | |
| end | |
| parts.push("/").push(name).join("/") | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment