【问题标题】:Create image from scratch with Ruby Vips使用 Ruby Vips 从头开始​​创建图像
【发布时间】:2020-12-26 14:41:28
【问题描述】:

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

我需要创建 1920x1920 的白色背景图像,在此处添加一些黑色文本并将其写入 tempfile。

如何用代码做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby vips


    【解决方案1】:

    这有点繁琐。用普通的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 制作alpha,然后添加一个纯色块作为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 的透明图像吗?还是只是透明背景上的一些彩色文字?
    • 说实话,需求变了。现在我只需要没有额外画布的文本。具有透明背景。
    • 您好,我又添加了一些示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多