Search code examples
ruby-on-railsrubyfontsrmagick

How can I generate fonts images using Rmagick?


In my app, there is a controller with a method for generate images from TrueType and OpenType files, which receives parameters like "color", "arbitrary text", "background".

The problem is when the path file contains white space:

def imagefont

  font = Font.find params[:font]
  file = File.basename font.file, File.extname(font.file)
  fontfile = File.path(Pathname.new("public/downloads/#{font.name.slice(0,1).capitalize}/#{file}/#{font.file}"))

  options = {
    :max_width  => 240,
    :text_color => params[:color],
    :font_size  => 35,
    :text       => params[:text],
    :bg_color   => params[:background],
    :font       => fontfile
  }

  if File.exists?(options[:font])

    canvas = Magick::Image.new 50, 50
    image = Magick::Draw.new

    begin

      image.annotate(canvas, 0, 0, 0, 0, options[:text]) do
        image.pointsize = options[:font_size]
        image.font = options[:font]
      end

      metrics = image.get_type_metrics canvas, options[:text]
      canvas = Magick::Image.new(metrics.width, metrics.height){ self.background_color = options[:bg_color] }

      options[:font_size] -= 1

    end while metrics.width > options[:max_width]

    image  = Magick::Draw.new
    image.font options[:font]
    image.font_size options[:font_size]
    image.fill options[:text_color]
    image.text 0, 0, options[:text]
    image.gravity = Magick::CenterGravity
    image.draw canvas

    temp = Tempfile.new([font.file, '.png'])
    canvas.write(temp.path)

    render :text => open(temp.path).read  

  end

end

The above code works, unless the font name contains whitespaces. In that case it displays the following error:

Magick::ImageMagickError in FontController#imagefont
non-conforming drawing primitive definition `Blick' @ error/draw.c/DrawImage/3146

In this case the font name is "A Blick for All Seasons", so I think it's a problem with quotes. I tried put simple quotes, but I wasn't successful.


Solution

  • I hadn't answers, but I got a possible solution. I found and I have modified the method in the gem files that receives the fontfile parameter. Initially appears thus:

    # File lib/RMagick.rb, line 335
    def font(name)
      primitive "font #{name}"
    end
    

    I've changed adding simple quotes and I got it, works fine:

    # File lib/RMagick.rb, line 335
    def font(name)
      primitive "font \'#{name}\'"
    end
    

    I think I should send a "pull request" with this change. Unless there is another answer.