2

I want to create a solid colored background canvas of a given size, using the methods available with Ruby-Vips. Right now, I am able to do so, like this:

canvas = Vips::Image.black(600, 600).ifthenelse([0,0,0], [252, 186, 3])

However, it seems strange to have to create a black image, then apply color pixel by pixel in this way. Is there a better or a more efficient way of accomplishing this?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
adam tropp
  • 674
  • 7
  • 22

1 Answers1

1

If you are trying to match an existing image, you can use new_from_image:

y = x.new_from_image [1, 2, 3]

Makes an image which copies most properties from x, but every pixel value is replaced by [1, 2, 3].

The source for new_from_image shows how to make an image efficiently from scratch:

    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

So:

  • make a one pixel black image
  • add the constant
  • cast to the desired format (uint8, double, etc.)
  • expand to the desired size
  • set metadata like resolution, interpretation, etc.
jcupitt
  • 10,213
  • 2
  • 23
  • 39
  • Sure enough, I benchmarked that against the example from the post, and it's about 3.5 times as fast. Thanks! – adam tropp Apr 09 '20 at 21:19