首页 > 解决方案 > 如何在 ruby​​ on rails 中将文本转换为图像

问题描述

基本上我想将一些内容显示为图像而不是 html,例如我想将用户的电话号码显示为图像。

但是如何将该文本转换为 Rails 中的图像?有没有可能?

标签: ruby-on-railsruby

解决方案


想到的最简单的解决方案是为此使用 Web 服务——例如https://textoverimage.moesif.com/。但根据您的描述,我认为您正在寻找这种解决方案的原因之一是隐私问题——因此与第三方网络服务共享电话号码似乎不是正确的方法。

下一个最好的方法是使用 ImageMagick 在动态创建的图像上简单地绘制文本。RMagick 库允许直接集成 Ruby 和 ImageMagick。使用页面 ( https://rmagick.github.io/usage.html#drawing_on ) 包含有关如何在图像上绘制文本的示例。然后,您可以调用图像的to_blob方法并使用 Railssend_data发送图像。生成的代码将如下所示(请注意,我正在对您的数据模型做出一堆假设,这些假设可能正确,也可能不正确):

class PhoneNumbersController < ApplicationController
  respond_to :png, only: :show

  def show
    phone_number = PhoneNumber.find(params[:phone_number_id])

    canvas = Magick::ImageList.new("number.png")
    text = phone_number.full_number # or whatever your full representation method is called
    # ... add the rest of the code based on the RMagick examples mentioned above

    send_data(canvas.to_blob, type: :png, disposition: :inline)
  end
end

推荐阅读