#!/usr/local/bin/ruby
require 'cgi'
require 'RMagick'

images = Dir["/home/hensleyl/images/*.jpg"]
name = images[rand(images.size)]

#load and crop photo
height = 88
width = 770
photo = Magick::ImageList.new(name)
photo.minify! if photo.columns > (width * 2)
photo.crop!(Magick::CenterGravity, width, height)


#create mask
mask = Magick::ImageList.new
mask.new_image(photo.columns, photo.rows) {self.background_color="black"}
smooth_box = Magick::Draw.new
smooth_box.stroke('white').fill('white')
smooth_box.roundrectangle(10, 10, width-10, height-10, 10, 10)
smooth_box.draw(mask)
mask = mask.gaussian_blur(1,1)

#composite photo to round and smooth the edges
mask.matte = false
photo.matte = true
comp = photo.composite(mask, Magick::CenterGravity, Magick::CopyOpacityCompositeOp)
comp.crop!(Magick::CenterGravity, width-16, height-16)

#draw text on the image
text = Magick::Draw.new
text.gravity(Magick::CenterGravity)
text.pointsize = 42
text.font = 'candy'
text.fill('black')
text.text(3, 3, '"Youth culture killed my dog"')
text.fill('#e0c0e0')
text.text(0, 0, '"Youth culture killed my dog"')
text.draw(comp)

#put it on a white background
background = Magick::ImageList.new
background.new_image(comp.columns, comp.rows) {self.background_color='white'}
final = background.composite(comp, Magick::CenterGravity, Magick::OverCompositeOp)

final.matte=false
final.write("banner.jpg") {self.quality = 90}

cgi = CGI.new("html4")
cgi.out {
  cgi.html {
   cgi.body {
     cgi.h3 { 'The new banner image is' } +
     cgi.br +
     cgi.img('banner.jpg') +
     cgi.br +
     cgi.a('banner_rotate.cgi') {'try another banner'} +
     ' | ' +
     cgi.a('index.cgi') {'back to the blog'}
   }
  }
}