У меня есть и приложение с драгоценными камнями 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
, чтобы сделать альфа-канал, затем добавьте блок сплошного цвета в качестве 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
Вам действительно нужно прозрачное изображение 1920 x 1080? Или просто цветной текст на прозрачном фоне?
Правда требования изменились. И теперь мне нужен только текст без дополнительного холста. С прозрачным фоном.
Привет еще раз, я добавил еще несколько примеров.
Спасибо! И как я могу сделать изображение с прозрачным фоном? Только цветной текст