Search code examples
rubyvips

How to efficiently create a solid colored background image with Ruby-Vips


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?


Solution

  • 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.