ruby-on-rails - Vips - 在 Ruby 中调整大小后在图像顶部添加文本

标签 ruby-on-rails ruby-on-rails-5 imagemagick shrine vips

我正在使用 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]);

最佳答案

你的例子看起来像 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 = shadow_mask.gaussblur(blur_radius / 2) if blur_radius > 0.1

# 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

制作:

enter image description here

关于ruby-on-rails - Vips - 在 Ruby 中调整大小后在图像顶部添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63947422/

相关文章:

ruby-on-rails - 无资源路由的 link_to 路径是什么?

ruby-on-rails - 我应该自己从文件系统中删除上传的文件吗?

mysql - 导轨数据库 :migrate doesn't work after altering the database manually

graphics - ImageMagick:将图像转换为黑白,高对比度!

linux - 在 Linux 上使用 image-magick 获取以毫米为单位的 PDF 大小

javascript - RequireJs + Rails 4

ruby-on-rails - 当在rails中使用 'build'命令时,在保存之前,我的zombie.weapons数组中有2个武器,但是zombie.weapons.count = 0

ruby-on-rails - 覆盖模型属性阅读器不会影响simple_form输入字段

javascript - jQuery : fire callback only once

pdf - 使用 imagemagick 无损旋转 PDF 文件