Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
129 lines (99 sloc) 2.8 KB
require 'sinatra/base'
require 'RMagick'
require 'newrelic_rpm'
class Placedog < Sinatra::Base
set :public, 'public/'
Pic = Struct.new( :image, :width, :height )
###
# Preload all pictures in the /images directory
###
def self.preload_pics
puts "Preloading pics"
start_time = Time.now
images = []
Dir.entries( './images/' ).collect{ |f| f if f =~ /\.jpg/ }.compact.each do |pic|
mag = Magick::Image.read( "images/#{pic}" ).first
p = Pic.new( mag, mag.columns, mag.rows )
images.push p
end
puts "#{images.count} images loaded in #{(Time.now - start_time).round(2)} seconds"
return images
end
def get_doggie_image( width, height )
img = get_random_image
while( img.columns < width || img.rows < height ) do
puts 'going for another'
img = get_random_image
end
multiplier = 0.0
puts "req: #{width}x#{height}"
multiplier = get_multiplier( img, width, height )
puts "orig: #{img.columns}x#{img.rows}"
img = img.thumbnail( img.columns*multiplier, img.rows*multiplier )
puts "thumb: #{img.columns}x#{img.rows}"
img = img.crop( Magick::CenterGravity, width, height )
puts "after: #{img.columns}x#{img.rows}"
if img.columns != 1 || img.rows != 1
return img
else
return nil
end
end
def get_multiplier( img, width, height )
height_multiplier = (height.to_f / img.rows).round( 6 )
width_multiplier = (width.to_f / img.columns.to_f).round( 6 )
multiplier = width_multiplier > height_multiplier ? width_multiplier : height_multiplier
multiplier = multiplier + 0.000002
puts "multiplier is: #{multiplier}"
multiplier
end
def get_random_image
return PICS[rand(PICS.count)].image
end
PICS = preload_pics
MAX_WIDTH = 4272
MAX_HEIGHT = 2848
get "/" do
erb :index
end
get "/css/style_dark.css" do
sass :stylesheet
end
get "/:width/:height" do
width = params[:width].to_i
height = params[:height].to_i
if not request_precheck( width, height )
"Invalid width or height"
else
image = get_doggie_image( width, height )
if image == nil
"Unknown error occured"
else
content_type 'image/png'
image.to_blob
end
end
end
get "/g/:width/:height" do
width = params[:width].to_i
height = params[:height].to_i
if not request_precheck( width, height )
"Invalid width or height"
else
image = get_doggie_image( width, height )
if image == nil
"Unknown error occured"
else
content_type 'image/png'
image = image.quantize( 256, Magick::GRAYColorspace )
image.to_blob
end
end
end
def request_precheck( width, height )
if width > MAX_WIDTH or height > MAX_HEIGHT
return false
end
return true
end
end
Jump to Line
Something went wrong with that request. Please try again.