【问题标题】:MiniMagick wrap text on imageMiniMagick 在图像上换行
【发布时间】:2019-01-14 20:12:33
【问题描述】:

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

我曾尝试使用来自heredrawlabelannotationcaption 方法,但没有一个能给我正确的结果。 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

这是我的结果: 我见过的最接近解决方案的是this,但太乱了。

有没有更好的办法?

【问题讨论】:

  • 我最终使用了this 答案,因为它给了我最佳/期望的行为

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


【解决方案1】:

对不起,我不知道 Minimagick。但是在 ImageMagick 命令行中有 label: 自动将文本适应某些尺寸,例如图像宽度。见https://imagemagick.org/Usage/text/#label。如果 MiniMagick 不直接支持,那么也许你可以使用 Ruby/Rmagick 命令。请参阅https://github.com/minimagick/minimagick(方法部分),假设 RMagick 支持 lab​​el:like 方法。请注意,使用 label: 和 caption: 您必须在透明背景上使用文本创建新图像,然后将其合成到原始图像上。

这是一个例子:

输入:

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


【讨论】:

    【解决方案2】:

    您需要将 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多