2012-05-28 26 views
1

在我的應用程序中,有一個控制器,具有從TrueType和OpenType文件生成圖像的方法,該文件接收「顏色」,「任意文本」,「背景」等參數。如何使用Rmagick生成字體圖像?

問題是,當該路徑文件中包含空格:

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 

上面的代碼工作,除非該字體的名稱中包含空格。在這種情況下,它會顯示以下錯誤:

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

在這種情況下,字體名稱爲「A Blick for All Seasons」,所以我認爲這是有引號的問題。我嘗試了簡單的引語,但我沒有成功。

+0

字體的名稱在單詞「Blick」的每一邊都包含星號? – x1a4

+0

不包括星號,沒有工作降價 –

回答

1

我沒有回答,但我得到了一個可能的解決方案。我發現並修改了接收字體文件參數的gem文件中的方法。因此,最初出現:

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

我已經改變了添加簡單的報價,我得到了它,做工精細:

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

我認爲我應該向「拉入請求」這種變化。除非另有答案。