代码之家  ›  专栏  ›  技术社区  ›  i_use_the_internet

最小化图像上的换行文字

  •  0
  • i_use_the_internet  · 技术社区  · 6 年前

    在rails 5.2.1中,我试图使用minimagick在图像上编写文本。问题是,对于长文本,它超出了图像宽度的限制。

    我试图使用 draw , label , annotation caption 方法从 here 但没有人给我正确的结果。 字幕 甚至不将文本添加到图像中。

    这是我的代码:

          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 但是太乱了。

    有更好的办法吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   fmw42    6 年前

    对不起,我不认识小美琪。但是在imagemagick命令行中有一个label:它自动将文本调整到某个维度,比如图像宽度。见 https://imagemagick.org/Usage/text/#label . 如果minimagick不直接支持这一点,那么您可以使用ruby/rmagick命令。见 https://github.com/minimagick/minimagick (方法部分),假设rmagick支持label:like方法。请注意,使用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