Skip to content

Instantly share code, notes, and snippets.

@auser
Created August 19, 2008 18:28
Show Gist options
  • Save auser/6212 to your computer and use it in GitHub Desktop.
Save auser/6212 to your computer and use it in GitHub Desktop.
class Image
attr_reader :src
def self.zoom_crop(src, max_width, max_height, out="thumbs/")
# Image details
new(src).zoom_crop(max_width, max_height, out)
end
def initialize(src)
@src = src
end
def zoom_crop(max_width, max_height, out)
opts = []
opts << (horizontal? ? resize_horizontal(max_width, max_height) : resize_vertical(max_width, max_height))
opts << "-crop #{max_width}x#{max_height}+0+0"
cmd = "mogrify #{opts.join(" ")} +repage -path #{out} #{src}"
`#{cmd}`
end
def resize_vertical(forced_width, forced_height)
new_width = forced_width
new_height = new_width * aspect_ratio
[
"-gravity 'north'",
"-resize #{new_width}x#{new_height}"
]
end
def resize_horizontal(forced_width, forced_height)
new_height = forced_height
new_width = new_height * aspect_ratio
[
"-gravity Center",
"-resize #{new_width}x#{new_height}"
]
end
def write(out)
image.write(out)
end
def aspect_ratio
@aspect_ratio ||= (vertical? ? (height/width) : (width/height)).to_f
end
def horizontal?
@horizontal ||= (width > height)
end
def vertical?
@vertical ||= (width <= height)
end
def width
@width ||= info.split("x")[0].to_f
end
def height
@height ||= info.split("x")[1].to_f
end
def info
@info ||= `identify #{src} | awk '{print $3}'`
end
def src
@src
end
end
# Quick test
output_dir = File.join(File.dirname(__FILE__), "thumbs")
Dir[File.join(File.dirname(__FILE__), "images")+"/*"].each do |path|
Image.zoom_crop(path, 150,130, output_dir)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment