Skip to content

Instantly share code, notes, and snippets.

@taf2
Created September 9, 2009 14:07
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 taf2/183742 to your computer and use it in GitHub Desktop.
Save taf2/183742 to your computer and use it in GitHub Desktop.
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
#
# allow users to request an image to be of a specific size
#
# e.g.
#
# /sized/#{siteid}-#{fileId}-x-y.png
#
class Sized
def self.call(env)
if env["PATH_INFO"] =~ /^\/sized/
path = env["PATH_INFO"].gsub(/\/sized\//,'')
parts = path.split('-')
site = parts[0]
filekey = parts[1]
width = parts[2]
height = parts[3]
ext = File.extname(path)
return [500, {"Content-Type" => "text/plain"}, ["Error invalid size request"]] if(width.nil? or height.nil? or filekey.nil? or site.nil?)
width = width.to_i
height = height.to_i
return [500, {"Content-Type" => "text/plain"}, ["Error invalid size request"]] if(width == 0 or height == 0 or width > 1023 or height > 768)
file_path = File.join(RAILS_ROOT,'public','files',site,"#{filekey}#{ext}")
#files = Dir["#{File.join(RAILS_ROOT,'public','files',site,filekey)}*.*"]
begin
new_path = File.join(RAILS_ROOT,'public','files',site,"#{filekey}-#{width}-#{height}#{ext}")
if File.exist?(new_path)
return [200, {"X-Accel-Redirect" => "/files/#{site}/#{filekey}-#{width}-#{height}#{ext}", "Content-Type" => "image/#{ext.gsub(/\./,'')}"},[]]
end
return [404, {"Content-Type" => "text/html"}, ["Not Found"]] if !File.exist?(file_path)
new_image = Magick::Image.read(file_path).first.resize_to_fill(width, height)
new_image.write(new_path) { self.quality = 70 }
#new_image.quantize(number_colors=512, # maybe this is an options?
# colorspace=Magick::RGBColorspace,
# dither=true,
# tree_depth=0,
# measure_error=true).write(new_path) { self.quality = 70 }
[200, {"X-Accel-Redirect" => "/files/#{site}/#{filekey}-#{width}-#{height}#{ext}", "Content-Type" => "image/#{ext.gsub(/\./,'')}"},[]]
rescue => e
STDERR.puts e.message
STDERR.puts e.backtrace.join("\n")
[200, {"X-Accel-Redirect" => "/files/#{site}/#{filekey}#{ext}", "Content-Type" => "image/#{ext.gsub(/\./,'')}"},[]]
end
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment