You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MiniMagick生成图片未加载指定字体问题求助

解决MiniMagick生成图片时字体不生效的问题

核心问题:参数顺序错误

ImageMagick的命令参数顺序直接影响执行逻辑,你当前生成的命令中,-font参数在-draw之后执行——而-draw绘制文本时需要先读取字体配置,这就导致字体设置完全没生效。

修复代码

调整UserUploader中MiniMagick命令的参数顺序,将font设置移到draw之前:

# frozen_string_literal: true

class UserUploader < ApplicationUploader
  include CarrierWave::MiniMagick

  def generate_image(text)
    tmp_path = File.join(Dir.tmpdir, "#{SecureRandom.hex}.png")

    MiniMagick::Tool::Convert.new do |img|
      img.size "500x200"
      img.xc "white"            # Background color
      img.gravity "Center"      # Center the text
      img.pointsize "36"        # Font size
      img.fill "black"          # Text color
      # 将font设置移到draw之前,确保绘制文本时已加载字体
      img.font "#{Rails.root.join('public', 'font', 'Franklin_Gothic_Heavy_Regular.ttf')}"
      img.draw "text 0,0 '#{text}'"
      img << tmp_path           # Save image to this path
    end

    File.open(tmp_path)  # Return file handle
  end
end

额外排查步骤

  1. 验证字体路径与权限
    执行命令确认字体文件存在且进程可读取:

    ls -l /Users/Documents/work/company/public/font/Franklin_Gothic_Heavy_Regular.ttf
    

    确保输出显示文件存在,且运行Rails的用户有读取权限。

  2. 终端直接测试命令
    用调整顺序后的命令在终端执行,验证字体是否生效:

    magick convert -size 500x200 xc:white -gravity Center -pointsize 36 -fill black -font /Users/Documents/work/company/public/font/Franklin_Gothic_Heavy_Regular.ttf -draw text 0,0 'Testing Font' /tmp/test_font.png
    

    打开生成的/tmp/test_font.png确认字体显示正确。

  3. 确认ImageMagick字体支持
    你的ImageMagick已包含freetype和fontconfig依赖,可通过以下命令列出系统可识别的字体:

    magick identify -list font
    

    如果目标字体不在列表中,可通过Fontconfig配置让系统全局识别该字体,或保持代码中绝对路径指定的方式。

内容的提问来源于stack exchange,提问作者user12763413

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:35:08