Created
April 20, 2012 19:54
-
-
Save MollsReis/2431343 to your computer and use it in GitHub Desktop.
Image processing server using Sinatra and MiniMagick
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
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 |
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
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