Time Sensitive Background
- Posted: 8 months ago
- Tags:code, ruby, website
- 0 comments
I just added a new feature to my website. If you notice, the top graphic is somewhat like a sky. Now it changes depending on the time of day you are visiting my website. However, I did not accomplish this by making multiple graphics, and changing them out. I actually wrote a new model for rails that uses the Imagemagick/MiniMagick image processing library to accomplish this. So every few minutes of the day when it is called it will actually tint the picture an appropriate shade. It also saves these images, so they only have to be generated once. Here is the code for the model:
require 'rubygems'
gem 'mini_magick'
require 'mini_magick'
class Tphoto
attr_accessor :time, :file
def initialize(time,file)
@filename = file
@noon = Time.parse("%Y-%m-%d " << "12:45:00")
distance = time.to_i - @noon.to_i
if(distance > 0) then
time = time - (distance * 2)
end
@seconds = time.strftime("%H%M").to_i/10
@viewurl = "/images/tphoto/#{@seconds}/#{@filename}"
unless File.exist?("#{RAILS_ROOT}/public/images/tphoto/#{@seconds}/#{@filename}")
generate_time(@seconds, @file)
end
end
def generate_time(seconds, file)
unless File.exist?("#{RAILS_ROOT}/public/images/tphoto/#{@seconds}")
Dir.mkdir("#{RAILS_ROOT}/public/images/tphoto/#{@seconds}")
end
image = MiniMagick::Image.from_file("#{RAILS_ROOT}/public/images/tphoto/#{@filename}")
image.combine_options do |c|
c.fill("#FFFFFF")
c.tint(seconds+10)
end
image.write("#{RAILS_ROOT}/public/images/tphoto/#{@seconds}/#{@filename}")
end
def viewurl
return @viewurl
end
def filepath
return "#{RAILS_ROOT}/public/images/tphoto/#{@seconds}/#{@filename}"
end
end
and here is the code for the controller:
class TphotoController < ApplicationController
def index
@time = Time.now
@tphoto = Tphoto.new(@time, "monday.jpg")
@response.headers['Last-Modified'] = Time.now.httpdate
@response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
@response.headers['Pragma'] = 'no-cache'
@response.headers['Expires'] = 'Thu, 19 Nov 1981 08:52:00 GMT'
send_file @tphoto.filepath, :type => 'image/jpeg', :disposition => 'inline'
end
end
