Skip to content

Instantly share code, notes, and snippets.

@ksss
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save ksss/20a2325b7a05df959c2e to your computer and use it in GitHub Desktop.

Select an option

Save ksss/20a2325b7a05df959c2e to your computer and use it in GitHub Desktop.
e.g) GET /{filename}/fit/300/300
module MrubyMiniMagick
class Convert
attr_accessor :opts
def initialize(src, dst)
@opts = []
@src = src
@dst = dst
end
%i(resize define gravity background extent thumbnail).each do |name|
define_method(name) do |value|
opts << "-#{name} #{value}"
end
end
def call(output = false)
cmd = "convert #{opts.join(' ')} #{@src} #{@dst}"
if output
`#{cmd}`
else
system(cmd)
end
end
end
end
class Processor
def initialize(root)
@root = root
end
def fill(filename, method, width, height)
file_path = "#{@root}/#{filename}"
size = "#{width}x#{height}"
dst = "#{file_path}_#{method}_#{width}_#{height}"
cmd = MrubyMiniMagick::Convert.new(file_path, dst)
cmd.define "jpeg:size=#{size}"
cmd.thumbnail size
cmd.call
ret = File.read(dst)
File.unlink dst
ret
end
def fit(filename, method, width, height)
file_path = "#{@root}/#{filename}"
size = "#{width}x#{height}"
dst = "#{file_path}_#{method}_#{width}_#{height}"
cmd = MrubyMiniMagick::Convert.new(file_path, dst)
cmd.define "jpeg:size=#{size}"
cmd.thumbnail "#{size}^"
cmd.gravity 'center'
cmd.extent size
cmd.call
ret = File.read(dst)
File.unlink dst
ret
end
end
r = Nginx::Request.new
uris = r.uri.split("/")
uris.shift
Nginx.return Nginx::HTTP_BAD_REQUEST if uris.length < 1
case uris[1]
when 'fit'
Nginx.rputs Processor.new(Nginx::Server.new.document_root).fit(*uris)
when 'fill'
Nginx.rputs Processor.new(Nginx::Server.new.document_root).fill(*uris)
end
Nginx.return Nginx::HTTP_OK
server {
listen 80;
server_name img.localhost;
root /path/to/doc/root;
location / {
mruby_content_handler /etc/nginx/conf.d/imagemagick.rb;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment