Created
January 7, 2010 02:39
-
-
Save ejschmitt/270921 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Something I have wanted to write for a while, | |
# takes text and converts to an image, very simple. | |
# Erick Schmitt - July 19, 2009 | |
module ImageText | |
require 'rubygems' | |
require 'fileutils' | |
require 'RMagick' | |
include Magick | |
def self.render(image_text, file_name = nil, user_options = {}, return_image = false) | |
options = { | |
:margin => 10, #[0, 0, 0, 0], # margin - css style | |
:background_color => 'white', | |
:color => 'black', | |
:font_weight => 100, | |
:font_family => 'Helvetica', | |
:font => nil, | |
:font_size => 32 | |
} | |
options.merge! user_options | |
default_file_name = image_text.gsub(/[^a-z0-9]/i,'_').squeeze('_').chomp('_') + '.png' | |
if File.directory? file_name | |
file_name = File.join file_name, default_file_name | |
end | |
file_name = default_file_name unless file_name | |
canvas = Magick::Image.new(300, 300){ self.background_color = 'transparent' } | |
text = Magick::Draw.new | |
text.font_family = options[:font_family] | |
text.font = options[:font] if options[:font] | |
text.font_weight = options[:font_weight] | |
text.pointsize = options[:font_size] | |
text.gravity = Magick::CenterGravity | |
text.annotate(canvas, 0,0,0,0, image_text) { | |
self.fill = options[:color] | |
} | |
canvas.trim!(true) | |
# the remaining code is just to apply a margin... | |
margin = options[:margin] | |
margin = Array.new(4,margin) if margin.kind_of? Fixnum | |
img_height = canvas.rows + margin[0] + margin[2] | |
img_width = canvas.columns + margin[1] + margin[3] | |
canvasBG = Magick::Image.new(img_width, img_height){ self.background_color = options[:background_color] } | |
canvasBG.composite!(canvas, margin[3], margin[0], Magick::OverCompositeOp) | |
# save it | |
canvasBG.write(file_name) { self.quality = 100 } | |
return file_name unless return_image | |
return [canvasBG, file_name] | |
end | |
end | |
# example: | |
# input_text = ARGV[0] | |
# ImageText.render(input_text, 'text.png', {:color => "#990000", :background_color => 'transparent'}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment