ruby-on-rails - 使用 Ruby Vips 从头开始创建图像
问题描述
我有 gems image_processing 和 ruby-vips 的应用程序。
我需要创建 1920x1920 的白色背景图像,在那里添加一些黑色文本并将其写入 tempfile。
我怎样才能用代码做到这一点?
解决方案
这有点繁琐。在普通的 ruby-vips 中,您可以编写:
#!/usr/bin/ruby
require "vips"
# make the background
# make a one-pixel image, 8-bit, white (255), monochrome (b_w means black and
# white)
image = (Vips::Image.black(1, 1) + 255).
cast("uchar").
copy(interpretation: :b_w)
# expand up to the size we need ... libvips can do this very quickly
image = image.embed(0, 0, 1920, 1080, extend: :copy)
# make the text image ... this will be a GA image (grey plus alpha)
# "text" makes an image with 0 for the background and 255 for the text, so we
# can use it as the alpha
alpha = Vips::Image.text("Hello, world!", dpi: 600)
# we want black text, so put black in the G of our GA image
g = Vips::Image.black(alpha.width, alpha.height)
# put the text alpha and colour layer together ... again, tag as a monochrome
# image
txt = g.bandjoin(alpha).
copy(interpretation: :b_w)
# composite the text on to the white background
final = image.composite(txt, "over", x: 100, y: 100)
final.write_to_file("x.png")
然后运行:
使用 image_processing,您可以将类似的内容放入实用程序方法中,并将其作为操作链的一部分运行。
您可以以类似的方式制作文本图像:调用text
以制作 alpha,然后添加一个纯色块作为 RGB。例如:
#!/usr/bin/ruby
require 'vips'
alpha = Vips::Image.text("", dpi: 600)
# make an image matching alpha, where each pixel has the specified value
rgb = alpha.new_from_image([10, 20, 100])
image = rgb.bandjoin(alpha)
puts "writing to x.png ..."
image.write_to_file "x.png"
制作:
您不需要使用普通的 RGB 块,当然,您可以执行以下操作:
#!/usr/bin/ruby
require 'vips'
alpha = Vips::Image.text("", dpi: 600)
rgb = (1..3).map {|i| Vips::Image.worley(alpha.width, alpha.height, seed: i)}
image = Vips::Image.bandjoin(rgb + [alpha])
puts "writing to x.png ..."
image.write_to_file "x.png"
制作:
text
还有很多其他功能。看:
https://www.rubydoc.info/gems/ruby-vips/Vips/Image#text-class_method
https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text
推荐阅读
- javascript - Leaflet.js:maxZoom 和 minZoom 不起作用
- c# - 如何在 Asp.Net Core 3.0 WebAPI 中启用 CORS
- javascript - 元素的类名在循环中未定义
- 的子节点
- openid - ADFS 2019 登录页面未重定向到我的应用程序
- amazon-web-services - 如何在仪表板中清除 aws 批处理作业历史记录
- python-3.x - 在熊猫中将几个替换语句组合成一个
- java - java - 在构造函数中创建时,如何在java中关闭ExecuterService..?
- java - 如何使用java Process知道文件是否关闭
- qt - QtQuick 2 中 BusyIndicator 的高 CPU 使用率
- java - 验证注释约束不起作用