ruby-on-rails - 如何在 ruby on rails 中将文本转换为图像
问题描述
基本上我想将一些内容显示为图像而不是 html,例如我想将用户的电话号码显示为图像。
但是如何将该文本转换为 Rails 中的图像?有没有可能?
解决方案
想到的最简单的解决方案是为此使用 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
推荐阅读
- ios - 如何在 UITableView 内的 UICollectionView 内获取数组数组并返回正确数量的项目?
- php - Laravel 同时动态连接不同的数据库
- java - 如何使用边框布局?
- excel - 使用图形 API 或其他 API 使用 VBA-Excel 从 O365 读取 O365 组成员
- angular - 受身份验证服务保护的多个布局路线无法正常工作
- scala - 最大化 cassandra 中 RDD 写入吞吐量的理想策略
- oracle-cloud-infrastructure - REST API 或 Java SDK,哪个更适合监控 Oracle 云计算 VM?
- ios - Alamofire Multiform 上传带参数的图片
- python - 在其他 python 列表的值中从 python 列表中查找字符串
- javascript - 如何使用 Angular 和 ng2-google-charts 在谷歌图表工具中将 SVG 图像作为注释