Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'rubygems'
require 'RMagick'
require 'rvg/rvg'
include Magick
require 'picture'
RVG::dpi = 72
class PictureGenerator
def initialize(input, add_text=true, blur_amount=2)
@input = input
@picture = Picture.new(@input)
@size = @picture.size
@add_text = add_text
@blur_amount = blur_amount
end
def generate_picture
rvg = generate_rvg
rvg = render_rvg(rvg)
rvg = blur_rvg(rvg, @blur_amount) unless @blur_amount == 0
save_picture(rvg)
message 'Done!'
end
private
def generate_rvg
message "Generating picture \"#{@input}\" containing #{@picture.boxes.size} boxes, size #{@size}x#{@size} ..."
RVG.new(@size, @size).viewbox(0, 0, @size, @size) do |canvas|
add_background(canvas)
add_boxes(canvas)
add_text(canvas) if @add_text
end
end
def add_background(canvas)
canvas.background_fill = @picture.background_colour
end
def add_boxes(canvas)
@picture.boxes.each do |box|
add_box(canvas, box)
end
end
def add_box(canvas, box)
canvas.g.translate(box.x, box.y) do |shape|
shape.rect(box.width, box.height).styles(
:fill=> box.colour,
:fill_opacity => box.opacity,
:stroke => box.stroke_colour,
:stroke_width => box.stroke_width,
:stroke_opacity => box.stroke_opacity)
end
end
def add_text(canvas)
message "Adding input text ..."
canvas.text(@size / 2, @size - 100) do |title|
title.tspan(@input).styles(
:text_anchor => 'middle',
:font_size => @size / 7,
:font_family => 'helvetica',
:font_weight => 900,
:fill => 'white',
:stroke => 'black',
:stroke_width => @size / 100,
:opacity => 0.2,
:stroke_opacity => 0.05)
end
end
def render_rvg(rvg)
message "Rendering ..."
rvg.draw
end
def blur_rvg(rvg, amount)
message "Adding blur with radius #{amount} ..."
rvg.blur_image(amount, amount)
end
def save_picture(rvg)
message 'Saving picture ...'
rvg.write("output/#{@input.gsub(/[^\w|#|@|_]+/, '-')}.png")
end
def message(msg)
puts
puts msg
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.