如何解决如何在Rails上的ruby中将文本转换为图像
基本上我想将某些内容显示为图像而不是html,例如,我希望将用户的电话号码显示为图像。
但是如何将文本转换为Rails中的图像?有可能吗?
解决方法
想到的最简单的解决方案是为此使用网络服务。 https://textoverimage.moesif.com/。但是根据您的描述,我认为您正在寻找这种解决方案的原因之一就是隐私问题–因此,与第三方网络服务共享电话号码似乎并不是正确的选择。>
下一个最好的方法是使用ImageMagick在运行中创建的图像上简单地绘制文本。 RMagick库允许将Ruby和ImageMagick进行非常直接的集成。使用页面(https://rmagick.github.io/usage.html#drawing_on)包含有关如何在图像上绘制文本的示例。然后,您可以只调用图像的to_blob
方法并使用Rails的send_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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。