Vips — добавить текст поверх изображения после изменения размера в Ruby

Я использую Vips для изменения размера изображений через Shrine, надеясь, что можно использовать библиотеку Vips для объединения слоя текста поверх изображения.

ImageProcessing::Vips.source(image).resize_to_fill!(width, height)

Этот код отлично работает, как я могу добавить слой текста после resize_to_fill?

Цель состоит в том, чтобы написать «Hello world» белым текстом с тенью текста CSS в центре изображения.

Я пытался написать что-то вроде этого, но пока получаю только ошибки:

Vips\Image::text('Hello world!', ['font' => 'sans 120', 'width' => $image->width - 100]);

person Kobius    schedule 17.09.2020    source источник
comment
Здесь могут помочь некоторые примеры: libvips.blogspot.com/2016/01/   -  person dkam    schedule 18.09.2020


Ответы (1)


Ваш пример выглядит как PHP - в Ruby вы бы написали что-то вроде:

text = Vips::Image.text 'Hello world!', font: 'sans 120', width: image.width - 100

Я сделал демо для вас:

#!/usr/bin/ruby

require "vips"

image = Vips::Image.new_from_file ARGV[0], access: :sequential

text_colour = [255, 128, 128]
shadow_colour = [128, 255, 128]
h_shadow = 2
v_shadow = 5
blur_radius = 10

# position to render the top-left of the text
text_left = 100
text_top = 200

# render some text ... this will make a one-band uchar image, with 0 
# for black, 255 for white and intermediate values for anti-aliasing
text_mask = Vips::Image.text "Hello world!", dpi: 300

# we need to enlarge the text mask before we blur so that the soft edges 
# don't get clipped
shadow_mask = text_mask.embed(blur_radius, blur_radius,
                              text_mask.width + 2 * blur_radius,
                              text_mask.height + 2 * blur_radius)

# gaussblur() takes sigma as a parameter -- approximate as radius / 2
shadow_mask = blur_radius > 0.1 ? 
                shadow_mask.gaussblur(blur_radius / 2) : shadow_mask

# make an RGB image the size of the text mask with each pixel set to the
# constant, then attach the text mask as the alpha
rgb = text_mask.new_from_image(text_colour).copy(interpretation: "srgb")
text = rgb.bandjoin(text_mask)

rgb = shadow_mask.new_from_image(shadow_colour).copy(interpretation: "srgb")
shadow = rgb.bandjoin(shadow_mask)

# composite the three layers together
image = image.composite([shadow, text], "over",            
                        x: [text_left + h_shadow, text_left],
                        y: [text_top + v_shadow, text_top]) 

image.write_to_file ARGV[1]

Выполнить так:

$ ./try319.rb ~/pics/PNG_transparency_demonstration_1.png x.png

Делать:

введите здесь описание изображения

person jcupitt    schedule 18.09.2020