Permalink
Browse files

sinatra app

  • Loading branch information...
0 parents commit 5101389f75038ade1de0d2c82938ec90b219cebd @igrigorik committed Jan 15, 2011
Showing with 78 additions and 0 deletions.
  1. +39 −0 helper.rb
  2. BIN quote.png
  3. +39 −0 server.rb
@@ -0,0 +1,39 @@
+require 'rmagick'
+require 'rvg/rvg'
+
+include Magick
+
+module RMagickTextUtil
+ def render_cropped_text(caption_text, width_constraint, height_constraint, &block)
+ image = render_text(caption_text, width_constraint, &block)
+ if height_constraint < image.rows
+ percent = height_constraint.to_f / image.rows.to_f
+ end_index = (caption_text.size * percent).to_i # takes a leap into cropping
+ image = render_text(caption_text[0..end_index] + "...", width_constraint, &block)
+ while height_constraint < image.rows && end_index > 0 # reduce in big chunks until within range
+ end_index -= 80
+ image = render_text(caption_text[0..end_index] + "...", width_constraint, &block)
+ end
+ while height_constraint > image.rows # lengthen in smaller steps until exceed
+ end_index += 10
+ image = render_text(caption_text[0..end_index] + "...", width_constraint, &block)
+ end
+ while height_constraint < image.rows && end_index > 0 # reduce in baby steps until fit
+ end_index -= 1
+ image = render_text(caption_text[0..end_index] + "...", width_constraint, &block)
+ end
+ end
+ image
+ end
+
+ def render_text(caption_text, width_constraint, &block)
+ Magick::Image.read("caption:#{caption_text.to_s}") {
+ # this wraps the text to fixed width
+ self.size = width_constraint
+ # other optional settings
+ block.call(self) if block_given?
+ }.first
+ end
+end
+
+include RMagickTextUtil
BIN quote.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@@ -0,0 +1,39 @@
+require 'sinatra'
+require 'helper'
+
+get "/" do
+ text = 'sample text'
+ from = 'somesite'
+
+ quote = Image.read("quote.png").first
+
+ RVG::dpi = 72
+
+ bg = RVG.new(680.px, 480.px) do |canvas|
+ canvas.background_fill = 'black'
+ end.draw
+
+ text = render_cropped_text(text, 500, 430) do |img|
+ img.fill = "#ffffff" # font color
+ img.background_color = "transparent"
+ img.pointsize = 23
+ img.antialias = true
+ end
+
+ src = render_cropped_text(from, 500, 40) do |img|
+ img.fill = "#cccccc" # font color
+ img.background_color = "transparent"
+ img.pointsize = 18
+ img.antialias = true
+ end
+
+ quote.page = Rectangle.new(quote.rows,quote.columns,15,30)
+ text.page = Rectangle.new(text.rows,text.columns,105,65)
+ src.page = Rectangle.new(src.rows,src.columns,105,430)
+
+ r = ImageList.new
+ r << bg << quote << text << src
+
+ content_type 'image/png'
+ r.flatten_images.to_blob {|i| i.format = 'PNG'}
+end

0 comments on commit 5101389

Please sign in to comment.