使用 Ruby Vips 从头开始​​创建图像

问题描述

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

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

我如何用代码做到这一点?

解决方法

有点麻烦。简单的 ruby-vips 你可以这样写:

# Define function.
# Accepts either a single string argument or multiple strings via the pipeline.
function Test-Base64 {
  param(
    [Parameter(ValueFromPipeline)] 
    [string] $String
  )
  process {
    try { $null=[Convert]::FromBase64String($String); $true } catch { $false }
  }
}

# Test two sample strings.
foreach ($item in 'foo','SGFwcHkgSG9saWRheXM=') {
  if (Test-Base64 $item) {
    "YES: $item"
  }
  else {
    "NO: $item"
  }
}

然后跑来做这个:

enter image description here

使用 image_processing,您可以将类似的内容放入实用程序方法中,并将其作为操作链的一部分运行。

您可以用类似的方式制作文本图像:调用 #!/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,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") 制作 alpha,然后添加一个纯色块作为 RGB。例如:

text

制作:

enter image description here

您不需要使用普通的 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"

制作:

enter image description here

#!/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" 有很多其他功能。见:

https://www.rubydoc.info/gems/ruby-vips/Vips/Image#text-class_method

https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...