如何使用 Ruby-Vips 高效创建纯色背景图片
How to efficiently create a solid colored background image with Ruby-Vips
我想创建给定大小的纯色背景 canvas,使用 Ruby-Vips 可用的方法。现在,我可以这样做,就像这样:
canvas = Vips::Image.black(600, 600).ifthenelse([0,0,0], [252, 186, 3])
但是,必须创建一个黑色图像,然后以这种方式逐个像素地应用颜色,这似乎很奇怪。有没有更好或更有效的方法来实现这一点?
如果您要匹配现有图像,可以使用 new_from_image
:
y = x.new_from_image [1, 2, 3]
制作复制了 x
大部分属性的图像,但每个像素值都被 [1, 2, 3]
替换。
new_from_image
的来源展示了如何从头开始高效制作图像:
def new_from_image value
pixel = (Vips::Image.black(1, 1) + value).cast(format)
image = pixel.embed 0, 0, width, height, extend: :copy
image.copy interpretation: interpretation, xres: xres, yres: yres,
xoffset: xoffset, yoffset: yoffset
end
所以:
- 制作一个单像素的黑色图像
- 添加常量
- 转换为所需格式(uint8、double 等)
- 扩展到所需大小
- 设置分辨率、解释等元数据
我想创建给定大小的纯色背景 canvas,使用 Ruby-Vips 可用的方法。现在,我可以这样做,就像这样:
canvas = Vips::Image.black(600, 600).ifthenelse([0,0,0], [252, 186, 3])
但是,必须创建一个黑色图像,然后以这种方式逐个像素地应用颜色,这似乎很奇怪。有没有更好或更有效的方法来实现这一点?
如果您要匹配现有图像,可以使用 new_from_image
:
y = x.new_from_image [1, 2, 3]
制作复制了 x
大部分属性的图像,但每个像素值都被 [1, 2, 3]
替换。
new_from_image
的来源展示了如何从头开始高效制作图像:
def new_from_image value
pixel = (Vips::Image.black(1, 1) + value).cast(format)
image = pixel.embed 0, 0, width, height, extend: :copy
image.copy interpretation: interpretation, xres: xres, yres: yres,
xoffset: xoffset, yoffset: yoffset
end
所以:
- 制作一个单像素的黑色图像
- 添加常量
- 转换为所需格式(uint8、double 等)
- 扩展到所需大小
- 设置分辨率、解释等元数据