Skip to content

Instantly share code, notes, and snippets.

@awesome
Forked from EvilScott/image_resizer.rb
Created April 3, 2014 21: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 awesome/9963024 to your computer and use it in GitHub Desktop.
Save awesome/9963024 to your computer and use it in GitHub Desktop.
require 'mini_magick'
class ImageResizer
attr_accessor :height, :width, :padding, :stretch, :grayscale
def initialize(path)
@image = MiniMagick::Image.open(path)
end
def image_format
@image[:format]
end
def to_s
process!
@image.to_blob
end
private
def process!
# grayscale the image
@image.colorspace 'gray' if @grayscale
# bail out if there are no dimensions to play with
return if @height.nil? && @width.nil?
# keep default dimensions if not given new ones
@width = @image[:width] if @width.nil? || @width <= 0
@height = @image[:height] if @height.nil? || @height <= 0
# ignore the aspect ratio
if !!@stretch
@image.resize "#{@width}x#{@height}!"
# add padding
elsif !!@padding
@image.combine_options do |opts|
opts.extent "#{@width}x#{@height}"
opts.gravity 'center'
opts.background 'white'
end
# resize with aspect ratio
else
@image.resize "#{@width}x#{@height}>"
end
end
end
require 'sinatra'
require 'haml'
require './image_resizer'
$image_param_hash = {
:stretch= => 's',
:padding= => 'p',
:grayscale= => 'g',
:width= => /^w(\d+)$/,
:height= => /^h(\d+)$/
}
get '/:dir/:image' do
# split out filename and image params
image_params = params[:image].split('.')
filename = "#{image_params.shift}.#{image_params.pop}"
path = "/www/images/#{params[:dir]}/#{filename}"
# 404 on missing images
not_found unless File.exists? path
# parse the image params and apply changes
image = ImageResizer.new(path)
$image_param_hash.each do |meth, param|
if param.is_a?(String) && image_params.include?(param)
image.send(meth, true)
elsif param.is_a?(Regexp)
image.send(meth, $1.to_i) if image_params.find { |ip| ip =~ param }
end
end
# render the image
content_type "image/#{image.image_format}"
image.to_s
end
get '/' do
haml :index
end
__END__
@@ index
!!!
%html
%head
%title RE-glass
:css
h1 {
margin: 200px auto 0;
width: 200px;
text-align: center;
}
%body
%h1 RE-glass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment