Skip to content

Instantly share code, notes, and snippets.

@ecavazos
Created January 17, 2010 20:24
Show Gist options
  • Select an option

  • Save ecavazos/279565 to your computer and use it in GitHub Desktop.

Select an option

Save ecavazos/279565 to your computer and use it in GitHub Desktop.
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