MiniMagick在图像上换行

时间:2019-01-14 20:12:34

标签: ruby-on-rails ruby image imagemagick minimagick

在Rails 5.2.1上,我试图使用MiniMagick在图像上书写文本。问题是,对于长文本,它超出了图像宽度的范围。

我尝试使用here中的drawlabelannotationcaption方法,但没有一个给我正确的结果。 caption甚至不将文本添加到图像。

这是我的代码:

      temp_img = MiniMagick::Image.open(url_for(@post.image))
      img_width = temp_img[:width]

      temp_img.combine_options do |c|
        c.gravity 'North'
        c.draw "text 0, 0 '#{top_txt}'"
        #c.annotate '0,0', "'#{top_txt}'" (same result)
        #c.caption "'#{top_txt}'" (same result)
        #c.label "'#{top_txt}'" (same result)
        c.gravity 'South'
        c.draw "text 0, 0 '#{bot_txt}'"
        #c.annotate '0,0', "'#{bot_txt}'" (same result)
        #c.caption "'#{bot_txt}'" (same result)
        #c.label "'#{bot_txt}'" (same result)
        c.stroke('#000000')
        c.strokewidth 1
        c.fill('#FFFFFF')
        c.size "#{img_width}x"
        c.pointsize '40'
        c.font "#{Rails.root.join('public', 'font',
        'Franklin_Gothic_Heavy_Regular.ttf')}"
      end

这是我的结果: enter image description here 我所看到的最接近解决方案的是this,但太乱了。

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

对不起,我不认识Minimagick。但是在ImageMagick命令行中有标签:该标签会自动使文本适合某个尺寸,例如图像宽度。参见https://imagemagick.org/Usage/text/#label。如果MiniMagick不直接支持它,那么您可以使用Ruby / Rmagick命令。假设{RMagick支持label:like方法,请参见https://github.com/minimagick/minimagick(方法部分)。请注意,带有label:和caption:您必须使用透明背景上的文字创建一个新图像,然后将其合成到原始图像上。

这里是一个例子:

输入:

enter image description here

convert image.png \( -size 639x -background none -font Arial -fill black label:"The quick brown fox jumps over the lazy dog" \) -gravity center -compose over -composite result.png


enter image description here

答案 1 :(得分:0)

您需要将Convert与MiniMagick一起使用,并且语法有些棘手,因为Ruby的示例并不多。

caption_string = "caption: #{top_txt}"

MiniMagick::Tool::Convert.new do |img|
  img.gravity 'north'
  img.stroke '#000000'
  img.strokewidth 1
  img.fill '#FFFFFF'
  img.size "#{img_width}x"
  img.pointsize '40' #don't add this if you want it to adjust according to size
  img.font "#{Rails.root.join('public', 'font',
    'Franklin_Gothic_Heavy_Regular.ttf')}"
  img << caption_string
  img << url_for(@post.image)
end