首页 > 解决方案 > 使用 Ruby Vips 从头开始​​创建图像

问题描述

我有 gems image_processing 和 ruby​​-vips 的应用程序。

我需要创建 1920x1920 的白色背景图像,在那里添加一些黑色文本并将其写入 tempfile。

我怎样才能用代码做到这一点?

标签: ruby-on-railsrubyvips

解决方案


这有点繁琐。在普通的 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


推荐阅读